(function ($) {
    var transferButton = false, errorFlag = false,
        maxHisMessageId = '',
        robotVersion = "",
        visitLoginCheck = false,
        isWework = false,
        feedbackTips = i18n.robot.feedbackTips,
        likeButton = false,
        likeButtonName = i18n.robot.likeButtonName,
        stepButton = false,
        stepButtonName = i18n.robot.stepButtonName,
        afterStepToShowTransferButton = false,
        transferName = i18n.robot.transferName,
        transferTips = i18n.robot.transferTips,
        isHiddenTransferHtml = true,
        allowRateForClientCloseSession = true,
        sessionRound = 3,
        orderHrefType = 0, //  orderHrefType 0: 为IFRAME方式打开   1: LOCATION方式打开
        roundTime = 0,
        fileUrl = '',
        ordersPageSize = 3,
        lastReplyIsDefault = false,
        ZTEDPGSSOUser = "",
        timerNum = 0,
        UCSSSOAccount = "",
        htmlForZTEStep = '<div id="sry" class="popdis" style="display: block;">' +
            '<div>' +
            '   <img src="images/dis.png" alt="对不起" width="120" height="100" style="float:left;">' +
            '    <p class="sorrytext">对不起，没能解决您的问题。<br>你的反馈会使我们下次做的更好！</p>' +
            '  </div>' +
            '  <div class="step-reason" style="clear: both;">' +
            '    <button class="but01 but" id="but01" type="button">方法行不通</button>' +
            '    <button class="but02 but" id="but02" type="button">答非所问</button>' +
            '    <button class="but03 but" id="but03" type="button">内容看不懂</button>' +
            '    <button class="but04 but" id="but04" type="button">内容太啰嗦</button>' +
            '  </div>' +
            '  <div>' +
            '    <p class="texttitle">有话要说（选填）</p>' +
            '    <textarea id="adviceInPopdis" placeholder="请输入任何想发表的意见或建议，我们一定会真诚对待~"></textarea>' +
            '  </div>' +
            '  <div style="text-align: center">' +
            '      <button class="cancel" type="button">取消</button>' +
            '      <button class="submit" type="submit">提交</button>' +
            '  </div>' +
            '  <button class="close" id="disclose"></button>' +
            '  <input type="hidden" id="queryInPopdis" value="">' +
            '  <input type="hidden" id="answerInPopdis" value="">' +
            '  <input type="hidden" id="accountInPopdis" value="">' +
            '</div>',
        htmlForYANXIStep = '',
        sessionRoundTips = i18n.robot.sessionRoundTips;
    if (typeof $config === 'undefined') {
        $config = {
            agent: true
        };
    }

    var ORDER_MESSAGE = i18n.robot.orderMessage;
    var robotEngineConfig;

    function getLikeAndStepButtonHtml(messageId, robotId, htmlData) {
        var html = "";
        if (likeButton || stepButton) {
            html += '<div class="rate-message likes" data-feedback="true">' +
                '<div>' +
                '<p>' + feedbackTips + '</p>';
            if (likeButton) {
                html += '<div class="like" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + htmlData + '><i></i>' + likeButtonName + '</div>';
            }
            if (stepButton) {
                html += '<div class="step" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + htmlData + '><i></i>' + stepButtonName + '</div>';
            }
            html += '</div></div>';
        }
        return html;
    }

    function sendMsgWithSearchKeyBase(msg, searchKey, extra) {
        if (msg) {
            if ($config.mobile) {
                sendMsgWithSearchKey(msg, searchKey, extra);
            } else {
                sendCommentWithSearchKey(msg, searchKey, extra);
            }
        }
    }

    function getNoticeForTransferMessage() {
        return '<dl class="message clearfix message-notice" data-click="true">' +
            '<div class="transfer-notices">' + transferTips + '</div>' +
            '</dl>';
    }

    function getNoticeForTransferMessageWhenRejectRecog() {
        return '<dl class="message clearfix message-notice session-round" data-click="true">' +
            '<div class="transfer-notices">' + wrapZRGForTips(sessionRoundTips) + '</div>' +
            '</dl>';
    }

    function getTransferClickHtml() {
        return '<a class="transfer-notice" data-click="true">' + transferName + '</a>';
    }

    function hiddenTransferHtml() {
        if (isHiddenTransferHtml) {
            $(".message-notice:not(.session-round)").hide();
        }
    }

    function wrapZRGForTips(tips) {
        var zrgRegExp = new RegExp(/\[ZRG](.*?)\[\/ZRG]/g);
        if (zrgRegExp.test(tips)) {
            tips = tips.replaceAll(zrgRegExp, '<span class="transfer-notice">$1</span>');
        }
        return tips;
    }

    function getTranseferButtonHtml(flag) {
        if (!flag && transferButton) {
            return '<hr>' +
                '<div class="transfer-message">' +
                '<p>转人工</p>' +
                '</div>'
        } else {
            return "";
        }
    }

    function getImageHtml(src, alt) {
        return '<image src="' + src + '" alt="' + alt + '" style="max-width: 300px; max-height: 300px;"/>';
    }

    function sendFeedback(data) {
        $.post("jsonHttpRemote.do", {requestType: "feedback", sessionId: $config.sessionId, data: data});
    }

    function stepHtml(dom, preCallback, callback) {
        if ($("#sry")[0]) $("#sry").remove();
        $("body").append(dom);
        preCallback();
        $(".popdis .but").off().click(function () {
            if ($(this).hasClass("active")) {
                $(this).removeClass("active");
            } else {
                $(this).addClass("active");
            }
        });
        $(".popdis .submit").off().click(function () {
            var reason = '';
            $.each($(".step-reason .active"), function (i, actives) {
                reason += $(actives).text() + ";";
            });
            var advice = $("#adviceInPopdis").val();
            isUseful = "true";
            callback({
                "reason": reason,
                "advice": advice,
            });
            $("#sry").remove();

        });
        $(".popdis .cancel").off().click(function () {
            $("#sry").remove();
        });
    }

    function feedbackFunc(feedType, $thisDom, userId) {
        var data = "";
        switch (userId) {
            case ROBOT_ID.ZTEROBOT:
                var account = $thisDom.data("account"),
                    query = $thisDom.data("query"),
                    answer = $thisDom.data("answer"),
                    reason = $thisDom.data("reason"),
                    advice = $thisDom.data("advice");
                var isUseful = "false";
                if (feedType == 1) {
                    isUseful = "true";
                    data = JSON.stringify({
                        "query": query,
                        "answer": answer,
                        "isUseful": isUseful,
                        "reason": reason,
                        "advice": advice,
                        "account": account
                    });
                    sendFeedback(data);
                } else {
                    stepHtml(htmlForZTEStep, function () {
                        $("#queryInPopdis").val(query);
                        $("#answerInPopdis").val(answer);
                        $("#accountInPopdis").val(account);
                    }, function (rate) {
                        var data = JSON.stringify({
                            "query": $("#queryInPopdis").val(),
                            "answer": $("#answerInPopdis").val(),
                            "isUseful": isUseful,
                            "reason": rate.reason,
                            "advice": rate.advice,
                            "account": $("#accountInPopdis").val()
                        });
                        sendFeedback(data);
                    });
                }

                break;
            case ROBOT_ID.EMOTIBOT:  //竹间机器人的反馈信息
                var uuid = $thisDom.data("uuid");
                if (feedType == 1) {
                    data = JSON.stringify({
                        "helpful": "helpful",
                        "content": "",
                        "uuid": uuid
                    });
                } else {
                    data = JSON.stringify({
                        "helpful": "unhelpful",
                        "content": "",
                        "uuid": uuid
                    });
                    //点踩的时候显示转人工提示信息
                    $thisDom.parent().html("<hr>" + getNoticeForTransferMessage());
                }
                sendFeedback(data);
                break;
            case ROBOT_ID.SINOROBOT:  //竹间机器人的反馈信息
                if (feedType == 1) {
                    data = JSON.stringify({
                        "solveStatus": "1",
                        "serviceLogId": $thisDom.data("servicelogid")
                    });
                } else {
                    data = JSON.stringify({
                        "solveStatus": "0",
                        "serviceLogId": $thisDom.data("servicelogid")
                    });
                    //点踩的时候显示转人工提示信息
                    $thisDom.parent().html("<hr>" + getNoticeForTransferMessage());
                }
                sendFeedback(data);
                break;
            case ROBOT_ID.SOBOT: //智齿机器人
                var docname = $thisDom.data("docname") || "",
                    msgid = $thisDom.data("msgid") || "",
                    uid = $thisDom.data("uid") || "",
                    cid = $thisDom.data("cid") || "",
                    docid = $thisDom.data("docid") || "";
                if (feedType == 1) {
                    data = JSON.stringify({
                        "status": "1",
                        "docname": docname,
                        "msgid": msgid,
                        "uid": uid,
                        "cid": cid,
                        "docid": docid
                    });
                } else {
                    data = JSON.stringify({
                        "status": "-1",
                        "docname": docname,
                        "msgid": msgid,
                        "uid": uid,
                        "cid": cid,
                        "docid": docid
                    });
                }
                sendFeedback(data);
                break;
            case ROBOT_ID.XIAOI:
                var data = $thisDom.data(), id = data.id, type = data.post, revoke = data.revoke;
                data = JSON.stringify({
                    "messageId": id,
                    "revoke": revoke,
                    "type": type
                });
                sendFeedback(data);
                break;
            case ROBOT_ID.YANXIBOT:
                var data = $thisDom.data()
                    , evaluateType = $thisDom.data().evaluatetype
                    , answerMessageId = $thisDom.data().answermessageid;
                if (feedType == 1) {
                    data = JSON.stringify({
                        "answerMessageId": answerMessageId,
                        "evaluateType": evaluateType,
                        "evaluateContent": '有用'
                    });
                    sendFeedback(data);
                } else {
                    if (htmlForYANXIStep) {
                        stepHtml(htmlForYANXIStep, function () {

                        }, function (rate) {
                            data = JSON.stringify({
                                "answerMessageId": answerMessageId,
                                "evaluateType": 0,
                                "evaluateContent": '没用'
                            });
                            sendFeedback(data);
                        });
                    } else {
                        data = JSON.stringify({
                            "answerMessageId": answerMessageId,
                            "evaluateType": 0,
                            "evaluateContent": '没用'
                        });
                        sendFeedback(data);
                    }
                }

                break;
        }
    };

    $(document).on("click", ".transfer-message", function () {
        console.log("转人工操作");
        $ROBOT.transferChat($config.queueId, "");
    }).on("click", ".message-title", function () {
        var id = $(this).attr("data-id"), title = $(this).attr("data-title"), preview = $(this).next().html(),
            question = $(this).attr("data-question");
        preview = wrapURL(preview);
        preview += getLikeAndStepButtonHtml("", ROBOT_ID.ZTEROBOT);
        if (!$config.mobile) {
            $F.appendTextToDiv("clientResponseDiv", '<div class="message clearfix me">' +
                '<div class="nowtime me-time"><span class="me-name">' + (Constants.client.clientFirstName || '访客') + '</span></div>' +
                '<div><img class="avatar" src="' + (Constants.client.iconUrl) + '" alt="' + Constants.client.iconAlt + '" /><i class="icon"></i></div>' +
                '<div class="contentBox"><div class="content">' + title + '</div></div>' +
                '</div>');
            $F.appendTextToDiv("clientResponseDiv", '<div class="message clearfix lele">'
                + '<div class="nowtime lele-time">'
                + '<span class="me-name">' + (Constants.robot.name || '人工客服') + '</span>'
                + '</div>'
                + '<div><img class="avatar" src="' + (Constants.robot.iconUrl) + '" alt="' + Constants.robot.iconAlt + '" /><i class="icon"></i></div>'
                + '<div class="contentBox"><div class="content">' + preview + '</div></div>' +
                '</div>');
        } else {
            appendTextToStandardDiv("clientResponseDiv", '<div class="user clear_box"  onload="setViewportScrollTop($(this).height());">' +
                '<div><img class="avatar" src="' + (Constants.client.iconUrl) + '" alt="' + Constants.client.iconAlt + '" /></div>' +
                '<div class="contentBox">' +
                '<p class="nickname">' + Constants.client.clientName +
                '</p>' +
                '<div class="content">' + title +
                '</div>' +
                '</div>' +
                '</div>', 1);
            appendTextToStandardDiv("clientResponseDiv", '<div class="custom_service clear_box"  onload="setViewportScrollTop($(this).height());"  data-id="">' +
            '<div><img class="avatar" src="' + (Constants.robot.iconUrl) + '" alt="' + Constants.robot.iconAlt + '" /></div>' +
            '<div class="contentBox">' +
            '<p class="nickname">' + Constants.agent.id ? Constants.agent.name : Constants.robot.name +
                '</p>' +
                '<div class="content">' + preview +
                '</div>' +
                '</div>' +
                '</div>', 1);
        }
    }).on("click", ".relate_body_li", function () {
        var $this = $(this), msg = $this.text()
            , msg = $this.data("msg") || msg
            , search = $this.data("search") || ''
            , extra = $this.data("extra") || '';
        sendMsgWithSearchKeyBase(msg, search, extra);
    }).on("click", ".send-message", function () {
        var cmd = $(this).data("cmd"), extra = $(this).data("extra") || '';
        if (cmd) {
            if ("zrg" == cmd) {
                $ROBOT.transferChat($config.queueId, "");
            }
        }
        var msg = $(this).data("message");
        var searchKey = $(this).data("key") || '';
        if (searchKey.startWith('faqvote')) {
            $(".send-message", $(this).parent()).removeClass("send-message");
        }
        sendMsgWithSearchKeyBase(msg, searchKey, extra);
    }).on("click", ".like", function () {
        var $rateMessage = $(this).parent().parent();
        var feedback = $rateMessage.data('feedback');
        if (feedback) {
            $rateMessage.data('feedback', false);
            var robotMessageId = $(this).data("id");
            var searchKey = $(this).data("search") || '';
            var msg = $(this).data("msg") || '';
            var extra = $(this).data("extra") || ''
            sendMsgWithSearchKeyBase(msg, searchKey, extra);
            $(this).children('i').addClass("active");
            console.log("对消息[" + robotMessageId + "]进行点赞处理")
            feedbackFunc(1, $(this), $(this).data("robotid"));
        }
    }).on("click", ".step", function () {
        var $rateMessage = $(this).parent().parent();
        var feedback = $rateMessage.data('feedback');
        if (feedback) {
            $rateMessage.data('feedback', false);
            var robotMessageId = $(this).data("botId")
                , searchKey = $(this).data("search") || ''
                , msg = $(this).data("msg") || ''
                , extra = $(this).data("extra") || ''
                , reason = $(this).data("reason") || false;
            searchKey = searchKey.replace('{4}', '');
            $(this).children('i').addClass("active");
            console.log("对消息[" + robotMessageId + "]进行点踩处理");
            if (reason) { //显示不满意的原因
                var $stepExtend = $('.step-extend', $rateMessage);
                // reason = JSON.parse(reason);
                if ($config.mobile) {
                    layer.open({
                        content: $stepExtend.html()
                        , className: 'confirm-mobile'
                        , btn: ['关闭']
                        , shadeClose: false
                        , yes: function (index) {
                            sendMsgWithSearchKeyBase(msg, searchKey, extra);
                            feedbackFunc(0, $(this), $(this).data("robotid"));
                            layer.close(index)
                        }
                    });
                } else {
                    $stepExtend.show();
                }
            } else {
                sendMsgWithSearchKeyBase(msg, searchKey, extra);
                feedbackFunc(0, $(this), $(this).data("robotid"));
                // if (afterStepToShowTransferButton) { // 如果配置了点击踩之后提示是否转人工的提示需要执行下面的代码
                //     if (!$config.mobile) {
                //         $F.appendTextToDiv("clientResponseDiv", getNoticeForTransferMessage());
                //     } else {
                //         appendTextToStandardDiv("clientResponseDiv", getNoticeForTransferMessage(), 1);
                //     }
                // }

            }
        }

    }).on("click", ".step-li", function () {
        var robotMessageId = $(this).data("botId")
            , searchKey = $(this).data("search") || ''
            , msg = $(this).data("msg") || ''
            , detail = (': ' + $(this).data("detail")) || ''
            , extra = $(this).data("extra") || '';
        $(this).children('i').addClass("active");
        $(this).addClass('active').parent().parent().hide();
        layer.closeAll();
        console.log("未解决扩展，对消息[" + robotMessageId + "]进行点踩处理");
        sendMsgWithSearchKeyBase(msg + detail, searchKey, extra);
        feedbackFunc(0, $(this), $(this).data("robotid"));
    }).on("click", ".show-iframeUrl", function () {
        var url = $(this).data("url");
        showNewBottomPage(url);
    }).on("click", ".transfer-notice", function () {
        var $messageNotice = $(this).parent().parent();
        if ($messageNotice.data('click')) {
            $messageNotice.data('click', false);
            console.log("点击转人工按钮转人工操作");
            if (visitLoginCheck && typeof loginWhenVisit == 'function') {
                loginWhenVisit(function () {
                    //显示对话框
                    $ROBOT.transferDialog("", function () {
                        $ROBOT.transferChat($config.queueId);
                    })
                })
            } else {
                if ($ROBOT.isPocVersion()) {
                    $("#popDiv").show();
                } else {
                    $ROBOT.transferDialog("", function () {
                        $ROBOT.transferChat($config.queueId, "");
                    })
                }
            }
    }
}).on("click", ".robot-ques li", function (event) {
    event.stopPropagation();
    var text = $(this).text();
    console.log("select remond questions ：" + text);
    if ($config.mobile) {
        sendMsg(text);
    } else {
        sendComment(text);
    }
    $(".robot-ques").hide();
}).on("click", ".message-card", function () {
    var url = $(this).data('url');
    if ($config.mobile) {
        showNewBottomPage(url);
    } else {
        window.open(url);
    }
}).on("click", ".message-imgtext, .message-orders", function () {
    var url = $(this).data('url')
        , text = $(this).data('send')
        , key = $(this).data("key")
        , hassend = $(this).data("hassend")
        , from = $(this).data("from")
        , funca = $(this).data("funca")
        , funci = $(this).data("funci")
        , keyFrom = $(this).data('keyfrom') || "";

    if (!hassend) {
        if (text) {
            sendMsgWithSearchKeyBase(text, key, 'orders')
        }
        if (from == 'uniqlo') {
            $('[data-keyfrom="' + keyFrom + '"]').data("hassend", "1");
        }
    }

    if (url) {
        if ($config.mobile) {
            if (orderHrefType == 0) {
                showNewBottomPage(url);
            } else {
                location.href = url;
            }

        } else {
            window.open(url);
        }
    }
    try {
        if (isIOS) {
            if (funci) {
                eval(funci);
            }
        } else {
            if (funca) {
                eval(funca);
            }
        }
    } catch (e) {
        console.log("error run function :" + e);
    }
}).on("click", ".orders-button", function () {
    var type = $(this).data("type"), parentData = $(this).parent()
        , messageOrders = parentData.parent().children('.message-orders')
        , page = parentData.data('page')
        , size = parentData.data('size');

    if (type == 'next') {
        if (0 < page + 1 && page + 1 < size) {
            parentData.data("page", ++page);
            $.each(messageOrders, function (i, orderDiv) {
                var index = orderDiv.dataset["index"];
                if (index == page) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            })
        }
    } else if (type == 'prev') {
        if (0 < page && page < size) {
            parentData.data("page", --page);
            $.each(messageOrders, function (i, orderDiv) {
                var index = orderDiv.dataset["index"];
                if (index == page) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            })
        }
    }
}).on("click", ".card-buttonItem", function () {
    var active = $(this).toggleClass("active");
}).on("click", ".card-btnSure", function () {
    var active = $(this).data("active");
    if (active == 'sure') {
        var robotCard = $(this).parents('.robot-card');
        var buttonItem = $('.card-buttonItem.active', robotCard);
        if (buttonItem.length > 0) {
            var arrSelect = [];
            $.each(buttonItem, function (i, item) {
                arrSelect.push($(item).data('title'));
            })
            var selectStr = arrSelect.join(";");
            sendMsg(selectStr)
        }
    }
});


/**
 * 去掉字符串中带有'CDATA'
 * @param str
 * @returns {*}
 */
function wrapCDATA(str) {
    var reg = new RegExp(/<\!\[CDATA\[([\S\s].*)\]\]>/i);
    while (reg.test(str)) {
        str = str.replace(reg, '$1').replace('<![CDATA[]]>', '');
    }
    return str;
}

function addclick(i, msg) {
    if (i != 0) {
        if (!$config.agent) {
            return '<a class="send-message" data-message="' + msg + '">' + '[' + i + '] ' + msg + '</a>';
        } else {
            return "<i>" + '[' + i + '] ' + msg + "</i>";
        }
    } else {
        if (!$config.agent) {
            return '<a class="send-message" data-message="' + msg + '">' + msg + '</a>';
        } else {
            return "<i>" + msg + "</i>";
        }
    }

};

function getRalateHtml(i, title, question, href, preview) {
    var html = "";
    if (!$config.agent) {
        html = '<div class="each-message">' +
            '<div class="message-title" data-title = "' + title + '" data-question = \'' + (title || question) + '\' >' +
            '<a data-url="' + href + '">' + (i + 1) + '. ' + (title || question) + '</a>' +
            '</div>';
        html += '<div class="message-preview" style="display: none">' + preview;
        if (href) {
            html += i18n.robot.showRalate.format('<a href="' + href + '" target="_blank">', '</a>');
        }
        html += '</div></div>';
    }
    return html;
}

var $ROBOT_MOBILE = {
    appendTextToDiv: function (divId, data) {
        var container = $("<div>").append(data);
        $("#" + divId).append(container);
        container.find("img:not(.thumb, .emot, .avatar, .tb-img, .ke-emoji)").each(function (i, img) {
            var imgObj = $(img);
            imgObj.css("cursor", "pointer").off("load").on("load", function () {
                autoResizeImage(300, 300, this);
                // setViewportScrollTop($("#clientResponseDiv").height());
                var scrollHeight = 0 - this.height;
                if (scrollHeight == 0) {
                    scrollHeight = -300;
                }
                if (hist == '1') {
                    setTimeout(function () {
                        setViewportScrollby(scrollHeight, 'img.load');
                    }, 500)
                }
            }).on("click", function () {
                showOriginImage(this);
                // $COMM.showOriginImage(this);
            });
        });

        $('.lele .avatar', container).on('error', function () {
            $(this).attr('src', 'jsp/standard/theme/' + $config.theme + '/img/agent.jpg');
        });

        $('.me .avatar', container).on('error', function () {
            $(this).attr('src', 'jsp/standard/theme/' + $config.theme + '/img/client.jpg');
        });
        // setViewportScrollTop($("#clientResponseDiv").height());
        scrollBottom("$ROBOT_MOBILE.appendTextToDiv")
    },
    formatNotice: function (msg) {
        return "<p class=\"messageTips\"><em>" + msg + "</em></p>";
    },
    formatNoticeForTransfer: function (msg) {
        return '<p class="messageTips transfer-message-tips"><em>' + msg + '</em></p>';
    }
}

var postQuestion = function (msg) {
    doAjaxCall(ajaxURL, "requestType=send&data=" + getPostMessageSentInfoJSON(encodeURIComponent(msg)), null);
};

function robotLog(text, from) {
    if (from)
        from = 'robotLog -> ' + from
    if (!$config.agent) {
        if ($config.mobile) {
            if (typeof text == 'object')
                console.log('from [%s]- %o', from, text);
            else
                console.log('from [%s]- %s', from, text);
        } else {
            if (typeof text == 'object')
                $F.log('from [' + from + ']-' + JSON.stringify(text));
            else
                $F.log('from [' + from + ']-' + text);
        }
    } else {
        console.log('from [' + from + ']-' + text);
    }

}

function handleKMData(text, flag) {
    var html = '';
    var question = text.question;
    var srs = text.srs;
    if (srs && srs.length > 0) {
        var href = 'javascript:;';
        $.each(srs, function (i, item) {
            if (item.ra)
                href = $ROBOT.wanUrl() + item.ra.path;
            else
                href = null;
            html += getRalateHtml(i, item.title, item.question, href, item.preview);
        });
    } else {
        html += text.message;
    }
    return html;
}

function handleXiaoDuoData(text, flag) {
    var show = false, transferFlag = false;
    var html = '';
    if (typeof text == 'string') {
        text = JSON.parse(text);
    }
    if (text.error_code == 0) {
        var data = text.data;
        if (data.transfer_to_kf) {
            if (!flag && typeof _mid == 'undefined') {
                if (data.transfer_to_kf_id) {
                    $ROBOT.transferChat(parseInt(data.transfer_to_kf_id), data.transfer_to_kf_id);
                } else {
                    $ROBOT.transferChat($config.queueId, "");
                }
                return html;
            } else {
                transferFlag = true;
            }
        }
        var state = data.state;
        if (state == 1 || state == 3) {
            var answers = data.answers;
            if (answers.length > 0) {
                robotLog("answer " + answers[0]);
                html += answers[0];
            }
            if (data.options) {
                var options = data.options;
                // if (html.length > 0) html += "<br>";
                $.each(options, function (i, option) {
                    robotLog("options[" + i + "] " + option);
                    html += addclick((i + 1), option);
                })
            }

            if (data.related_questions && data.related_questions.length > 0) {
                html += i18n.robot.relatedQuestions;
                $.each(data.related_questions, function (i, relatedQuestion) {
                    robotLog("relatedQuestion[" + i + "] " + relatedQuestion);
                    html += addclick((i + 1), relatedQuestion);
                })
            } else {
                if (data.hot_questions && data.hot_questions.length > 0) {
                    html += i18n.robot.hotQuestions;
                    $.each(data.hot_questions, function (i, hotQuestion) {
                        robotLog("hotQuestion[" + i + "] " + hotQuestion);
                        html += addclick((i + 1), hotQuestion);
                    })
                } else {
                    robotLog(i18n.robot.noAnswer);
                }
            }
        } else if (state == 2) {
            var recommends = data.recommend;
            if (recommends.length > 0) {
                html = i18n.robot.recommendsQuestions;
                $.each(recommends, function (i, recommend) {
                    robotLog("recommend[" + i + "] " + recommend);
                    html += addclick((i + 1), recommend);
                })
            } else {
                robotLog(i18n.robot.noAnswer);
            }
        } else {
            robotLog(i18n.robot.noAnswer);
        }
    } else {
        robotLog(i18n.robot.error.format(text.error_code));
    }
    if (transferFlag) html = "";
    return html;
}

function handleXiaoIData(messageId, text, flag) {
    $ROBOT.robotOrderObj = {};
    var show = false;
    if (robotVersion) show = true;
    try {
        var html = '';
        var content = "";
        if (text.result)
            text = text.result;
        if (text && text.content) {
            content = text.content;
        }
        if ('uniqlo' == robotVersion) {
            if (text.robotName) {
                Constants.robot.robotName = text.robotName;
            }
            if (text.robotType) {
                Constants.robot.robotType = text.robotType;
            }
        }
        switch (text.type) {
            case 0:
                if (!flag) {
                    if (robotVersion && typeof _mid == 'undefined') {
                        if (lastReplyIsDefault) {
                            if (roundTime >= sessionRound) {
                                $ROBOT.transferChat($config.queueId, "");
                            }
                        } else {
                            if (roundTime > 0) roundTime = 0;
                        }
                        lastReplyIsDefault = true;
                        if (lastReplyIsDefault) roundTime++;
                    }
                }
                html = content;
                break;
            case 1: //标准回复
                lastReplyIsDefault = false;
                var commands = text.commands;
                $.each(commands, function (c, args) {
                    var flagForState = false;
                    if ('uniqlo' == robotVersion) {
                        flagForState = true;
                    } else {
                        if (args.state == 1) {
                            flagForState = true;
                        }
                    }
                    if (flagForState) {
                        var name = args.name;
                        if ('txtmsg' == name.toLowerCase()) {
                            html += args.args;
                        } else if ('imgmsg' == name.toLowerCase()) {
                            var arg = args.args;
                            html += getImageHtml(arg[2], arg[0]);
                        } else if ('imgtxtmsg' == name.toLowerCase()) {  //图文信息
                            isNews = true;
                            if (args && args.args) {
                                var arg = args.args[3];
                                if (arg) {
                                    arg = arg.substring(9, arg.length - 3);
                                    var xmlDoc = $.parseXML(arg), $xml = $(xmlDoc), $item = $xml.find("item");
                                    html += domImageText.domImageTextHomeAppend();
                                    $.each($item, function (i, item) {
                                        var isFirst = false;
                                        if (i == 0) isFirst = true;
                                        html += domImageText.domImageText(wrapCDATA($(item).find('Title')[0].textContent),
                                            wrapCDATA($(item).find('Description')[0].textContent),
                                            wrapCDATA($(item).find('PicUrl')[0].textContent),
                                            wrapCDATA($(item).find('Url')[0].textContent), isFirst)
                                    })
                                    html += domImageText.domImageTextEndAppend();
                                }
                            }
                        } else if ('P4' == name.toUpperCase()) {
                            var arg = args.args;
                            html += '<a target="_blank" href="' + arg[0] + '">' + arg[1] + '</a>';
                        }
                    }
                });
                if (typeof content == "string") {
                    if (!html)
                        html += content;
                } else {
                    var contentType = content.type;
                    if ('uniqlo' == robotVersion) {
                        var size = content.size;
                        if (size > 0) {
                            var messageFormatOrder = '[MessageFormat data-type="orders" data-title="' + i18n.robot.orderTitle + '" data-key="uniqlo-' + new Date().getTime() + '" data-from="uniqlo"]';
                            var values = content.value;
                            var arrForOrder = [];
                            $.each(values, function (i, value) {
                                var orderst = value.orderStatus;
                                if (orderst == 'UNPAID') {
                                    orderst = '待付款';
                                } else if (orderst == 'CANCELLED') {
                                    orderst = '交易取消';
                                } else if (orderst == 'WAIT_SHIP') {
                                    orderst = '待发货/已付款';
                                } else if (orderst == 'WAIT_PICK') {
                                    orderst = '待自提';
                                } else if (orderst == 'PARTIAL_SHIP') {
                                    orderst = '部分发货';
                                } else if (orderst == 'SHIPPED') {
                                    orderst = '已发货';
                                } else if (orderst == 'FINISHED') {
                                    orderst = '交易成功';
                                } else if (orderst == 'CLOSED') {
                                    orderst = '交易关闭';
                                } else if (orderst == 'WAIT_DEPOSIT_PAY') {
                                    orderst = '定金未付尾款未付';
                                } else if (orderst == 'WAIT_REST_PAY') {
                                    orderst = '定金已付尾款未付';
                                } else if (orderst == 'REST_PAY_CANCELLED') {
                                    orderst = '定金已付交易取消';
                                }
                                arrForOrder.push({
                                    "content": value.productName,
                                    "key": i + 1,
                                    "title": value.productName,
                                    "imageUri": value.pictureUrl,
                                    "orderId": '订单' + value.orderId,
                                    "orderStatus": orderst,
                                    "size": value.size,
                                    "send": value.productName,
                                    "color": value.color,
                                    "quantity": value.quantity,
                                    "noReasonFlag": value.noReasonFlag,
                                    "price": value.actualUnitPrice || value.totalPrice
                                })
                            })
                            messageFormatOrder += JSON.stringify(arrForOrder);
                            messageFormatOrder += '[/MessageFormat]';
                            html = $ROBOT.parseFormattedMsg(messageFormatOrder);
                        }
                    }
                }
                break;
            case 101: //转人工客服
                lastReplyIsDefault = false;
                robotLog("转人工" + content);
                show = false;
                if (typeof content == "string") {
                    if (content && typeof _mid == 'undefined') {
                        if (content == 'SFYZ' || content == 'SJSFYZ' || content == 'SJYZ') {  //进行身份校验
                            if (!flag) {
                                //如果是小程序中的界面的话需要向小程序发送数据给小程序作为交互, 小程序收到数据之后做页面显示用
                                if (window.__wxjs_environment === 'miniprogram') { //判断是否是小程序
                                    var user = $config.user;
                                    if (user && user.stringfield16 == 'NO') {
                                        var urlOne = '/mainPackage/login/index?type=onlinechat&sessionid=' + $config.sessionId + '&custguid=' + $config.client.clientId;
                                        wx.miniProgram.navigateTo({
                                            url: urlOne,
                                            success: function () {
                                                wx.miniProgram.postMessage({
                                                    data: {
                                                        code: "success",
                                                        success: 'sendMessage is success'
                                                    }
                                                })
                                            },
                                            fail: function (e) {
                                                wx.miniProgram.postMessage({
                                                    data: {
                                                        code: "fail",
                                                        fail: e
                                                    }
                                                })
                                            }
                                        })
                                    } else if (user && user.stringfield16 == 'YK') {
                                        var urlTwo = '/mainPackage/register/stepTwo?type=onlinechat&userType=potentialCustomer&sessionid=' + $config.sessionId + '&custguid=' + $config.client.clientId;
                                        wx.miniProgram.navigateTo({
                                            url: urlTwo,
                                            success: function () {
                                                wx.miniProgram.postMessage({
                                                    data: {
                                                        code: "success",
                                                        success: 'sendMessage is success'
                                                    }
                                                })
                                            },
                                            fail: function (e) {
                                                wx.miniProgram.postMessage({
                                                    data: {
                                                        code: "fail",
                                                        fail: e
                                                    }
                                                })
                                            }
                                        })
                                    }
                                } else { //非小程序的时候是直接打开配置的身份校验的地址的
                                    var url = $config.queue.sfjyUrl + '&f1=' + $config.client.clientId + '&f2=' + $config.sessionId + '&f3=' + content;
                                    if ($config.mobile)
                                        setContentIframe(url);
                                    else
                                        window.open(url);
                                }
                            }
                        } else if (content.indexOf("ZRG") > -1) {
                            if (!flag && typeof _mid == 'undefined' && messageId > maxHisMessageId) {
                                if (!_transfering) {
                                    $ROBOT.transferChat($config.queueId, content);
                                }
                            } else {
                                html = ORDER_MESSAGE;
                            }
                        } else {
                            if ($config.sfyzUrl) {
                                $.post("jsp/standard/robotZrgContentManager.jsp", {
                                    "queue": $config.queueId,
                                    "content": content,
                                    "userid": $config.client.clientId,
                                    "sessionid": $config.sessionId
                                }, function (data) {
                                    if (typeof data == 'object') {
                                        if (data && data.message) {
                                            if ($config.mobile) {
                                                $ROBOT_MOBILE.appendTextToDiv("clientResponseDiv", $ROBOT_MOBILE.formatNotice(data.message));
                                            } else {
                                                $F.formatAndShowNotice(data.message);
                                            }
                                        }
                                        if (data && data.code && data.code == 'CLOSECHAT') {
                                            if (!flag) {
                                                if (!_sessionActive) {
                                                    endSessionBtnClickHandler();
                                                }
                                            } else {
                                                html = ORDER_MESSAGE;
                                            }
                                        }
                                    } else {
                                        try {
                                            data = JSON.parse(data);
                                            if (data && data.message) {
                                                if ($config.mobile) {
                                                    $ROBOT_MOBILE.appendTextToDiv("clientResponseDiv", $ROBOT_MOBILE.formatNotice(data.message));
                                                } else {
                                                    $F.formatAndShowNotice(data.message);
                                                }
                                            }
                                            if (data && data.code && data.code == 'CLOSECHAT') {
                                                if (!flag) {
                                                    if (!_sessionActive) {
                                                        endSessionBtnClickHandler();
                                                    }
                                                } else {
                                                    html = ORDER_MESSAGE;
                                                }
                                            }
                                        } catch (e) {
                                            if (!data.startWith("<")) {
                                                if ($config.mobile) {
                                                    $ROBOT_MOBILE.appendTextToDiv("clientResponseDiv", $ROBOT_MOBILE.formatNotice(data));
                                                } else {
                                                    $F.formatAndShowNotice(data);
                                                }
                                            }
                                        }
                                    }
                                });
                            } else {
                                html += content;
                            }
                        }
                    }
                } else {
                    if (!flag) {
                        if (content.acs) {
                            if (messageId > maxHisMessageId) {
                                _continueChat.can = true;
                                var url = Constants.lm.hrefClick || Constants.lm.hrefUrl;
                                // if (url) location.href = url + '&sessionId=' + $config.sessionId + '&cmdType=' + encodeURIComponent(JSON.stringify(content));
                                if (url) {
                                    url = url + '&sessionId=' + $config.sessionId + '&cmdType=' + encodeURIComponent(JSON.stringify(content));
                                    if ($config.mobile)
                                        setContentIframe(url);
                                    else
                                        window.open(url);
                                }
                            }

                        }
                    }
                }

                // else {
                //     $ROBOT.transferChat($config.queueId, '');
                // }
                break;
            default:
                lastReplyIsDefault = false;
                html = content;
                break;
        }
        if (show) {
            var relatedQuestions = text.relatedQuestions;
            if (relatedQuestions && relatedQuestions.length > 0) {
                html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
                html += '<div class="relate_body"><ul>';
                $.each(relatedQuestions, function (j, item) {
                    html += '<li><a class="relate_body_li">' + item + '</a></li>'
                    $ROBOT.robotOrderObj[j] = item;
                })
                html += '</ul></div>';
            }
        }

        if ('uniqlo' == robotVersion) {
            if (text.buttonList) {
                var buttonList = text.buttonList;
                if (buttonList.length > 0) {
                    if (text.type != 11)
                        html += '<div class="relate_title">' + i18n.robot.relatedButtonListTitle + '</div>';
                    $.each(buttonList, function (j, button) {
                        html += '<li><a class="relate_body_li"' +
                            ' data-msg="' + button.name + '"' +
                            ' data-search="' + button.question + '"' +
                            ' data-extra="' + button.type + '"' +
                            ' >' + button.name + '</a></li>'
                        $ROBOT.robotOrderObj[j] = button.question;
                    })
                }
            }
        }
        return html;
    } catch (e) {
        robotLog(e.message, 'on handleXiaoIData')
        return '';
    }
}

function handleYibotData(text, flag) {
    var html = '';
    if (text.status == 0) {
        if (text.type == 200) {
            var result = text.info[0];
            if (result.answer == 'zrg') {//转人工
                if (!$config.hasCreateChat) {
                    if (!flag && typeof _mid == 'undefined') {
                        robotLog("转人工操作");
                        if ($config.mobile) {
                            $ROBOT.transferChat($config.queueId);
                        } else {
                            $F.showConfirm(tip, function () {
                                // TODO 弹框提示是否需要转接到人工坐席
                                $ROBOT.transferChat($config.queueId);
                            });
                        }
                    } else {
                        html = ORDER_MESSAGE;
                    }
                    $config.hasCreateChat = true;
                } else {
                    domImageText.setNotices(i18n.robot.hasTransferAgent);
                    delayNotice();
                }
                return;
            }
            if ('image-text' == result.answerType) {
                var answerjson = result.answerjson;
                if (answerjson.length > 0) {
                    isNews = true;
                    html += domImageText.domImageTextHomeAppend();
                    $.each(answerjson, function (i, item) {
                        var isFirst = false;
                        if (i == 0) isFirst = true;
                        html += domImageText.domImageText(item.title, item.desc, item.pic_url, item.url, isFirst)
                    })
                    html += domImageText.domImageTextEndAppend();
                }
            } else if ("single-image" == result.answerType) {
                var imageUrl = result.pic_url;
                html = getImageHtml(imageUrl, "");
            } else {
                html = result.answer;
            }

            var relate = result.relate;
            if (relate && relate.length > 0) {
                html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
                html += '<div class="relate_body"><ul>';
                $ROBOT.robotOrderObj = {};
                $.each(relate, function (j, item) {
                    html += '<li><a href="javascript:void(0);" class="relate_body_li">' + item.qt + '</a></li>'
                })
                html += '</ul></div>';
            }
        } else if (text.type == 300) {
            var resultArr = text.info;
            if (resultArr) {
                html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
                $.each(resultArr, function (i, result) {
                    html += domAnswerTitleAppend(result.question, result.question, result.answer, i);
                })
            }
        } else if (text.type == 400) {  //机器人调用接口返回的结果
            var resultArr = text.info;
            $.each(resultArr, function (i, info) {
                if (info && info.answer) {
                    var answers = info.answer;
                    if ($.isArray(answers)) {
                        $.each(answers, function (i, answer) {
                            if (answer) {
                                html += numberConvertToUppercase(i + 1) + ':';
                                var policeRs = i18n.common.robotTemplateForPolicy;
                                $.each(answer, function (key, value) {
                                    policeRs = policeRs.replaceAll("{" + key + "}", value)
                                })
                                html += policeRs;
                            }
                        })
                    }
                }
            })
        } else {
            robotLog('YiBot 接口异常，请联系开发人员。');
            domImageText.setNotices(i18n.robot.error);
            delayNotice();
        }
        var relate = text.relate;
        if (relate && relate.length > 0) {
            html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
            html += '<div class="relate_body"><ul>';
            $ROBOT.robotOrderObj = {};
            $.each(relate, function (j, item) {
                html += '<li><a href="javascript:void(0);" class="relate_body_li">' + item.qt + '</a></li>'
            });
            html += '</ul></div>';
        }
        if (!flag) {
            var showNoticeForTransferMessage = false;
            var showNoticeForTransferMessageWhenRejectRecog = false;

            if (text.session_round) {
                var selfSessionRound = text.session_round
                if (selfSessionRound == sessionRound) {
                    showNoticeForTransferMessage = true;
                }
            }
            if (!showNoticeForTransferMessage && text.reject_recog) {
                var rejectRecog = text.reject_recog
                if (rejectRecog == 1) {
                    showNoticeForTransferMessage = true;
                    showNoticeForTransferMessageWhenRejectRecog = true;
                }
            }
            if (showNoticeForTransferMessage) {
                if (showNoticeForTransferMessageWhenRejectRecog) {
                    html = html + getNoticeForTransferMessage();
                } else {
                    html = html + getNoticeForTransferMessageWhenRejectRecog();
                }
            }
        }
    }

    return html;
}

function handleSobotData(text, flag) {
    var html = "";
    if (text && text.code == '1000') {
        var data = text.data;
        if (data && data.answer) {
            html = data.answer;
        }
        var suggestions = data.suggestions;
        if (suggestions && suggestions.length > 0) {
            if (data.stripe) {
                html += '<div class="relate_title">' + data.stripe + '</div>';
            } else {
                html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
            }
            $.each(data.suggestions, function (i, suggestion) {
                var answer = suggestion.answer;
                answer += getTranseferButtonHtml(flag);
                // html += getRalateHtml(i, suggestion.question, suggestion.question, "", answer);
                html += addclick(i + 1, suggestion.question);
            })
        }

        if (!flag) {
            html += getTranseferButtonHtml(flag);
            var htmlData = ' ';
            if (data.docId) {
                htmlData += 'data-docid="' + data.docId + '" ';
            }
            if (data.msgId) {
                htmlData += 'data-msgid="' + data.msgId + '" ';
            }
            if (data.cid) {
                htmlData += 'data-cid="' + data.cid + '" ';
            }
            if (data.uid) {
                htmlData += 'data-uid="' + data.uid + '" ';
            }
            if (data.question) {
                htmlData += 'data-docname="' + data.question + '" ';
            }
            html += getLikeAndStepButtonHtml("", ROBOT_ID.SOBOT, htmlData);
        }
    } else {
        html = i18n.robot.error;
    }
    return html;
}

function handleElitebotData(text, flag) {
    var html = "";
    if (text && text.code == 1) {
        var value = text.value;
        if (value.msgtype == "text") {
            var text = value.text;
            if (text) {
                html = wrapURL(text.content);
            } else {
                html = i18n.robot.noAnswer;
                html += getTranseferButtonHtml(flag);
            }
        } else if (value.msgtype == "image") {
            var image = value.image;
            if (image) {
                var src = robotEngineConfig.serverUrl + "/image?file=" + image.media_id;
                html = getImageHtml(src, '');
            } else {
                html = i18n.robot.noImage;
                if (!flag) {

                }
            }
        } else if (value.msgtype == 'news') {
            var news = value.news;
            if (news) {
                var articales = news.articles;
                if (articales.length > 0) {
                    var property = robotEngineConfig.property;
                    var baseUrl = "";
                    if (property) {
                        baseUrl = property.baseUrl;
                    }
                    html += domImageText.domImageTextHomeAppend();
                    $.each(articales, function (i, article) {
                        var picurl = article.picurl;
                        if (!picurl.startWith('http')) {
                            picurl = baseUrl + picurl;
                        }
                        var description = article.description;
                        var title = article.title;
                        var url = article.url;
                        var isFirst = false;
                        if (i == 0) {
                            isFirst = true;
                        }
                        html += domImageText.domImageText(title, description, picurl, url, isFirst)
                    })
                    html += domImageText.domImageTextEndAppend();
                }

            }
        } else if ('music' == value.msgtype) {

        } else if ('video' == value.msgtype) {
            var video = value.video;
            var src = robotEngineConfig.serverUrl + "/video?file=" + video.media_id;
            html += "<video src='" + src + "'>"
        } else {
            html = value;
        }
    } else {
        html = text.message || i18n.robot.error;
    }
    return html;
}

function handleEbossKMbotData(text, flag) {
    var feedback = {
        topNum: 1,
    };
    var html = "";
    if (text && text.success) {
        var data = text.data;
        if (data) {
            if (data.question) {
                feedback.question = data.question;
            }
            html = data.answer;
            if (data.label) {
                feedback.chooseLabel = data.label;
                feedback.topLabel = data.label;
            }
            var turnToSomeb = data.turnToSomeb;
            if (turnToSomeb && typeof _mid == 'undefined') {
                $ROBOT.transferChat($config.queueId, "");
            }
        } else {
            html = text.alertMsg || i18n.robot.noAnswer;
        }
    } else {
        html = text.alertMsg || i18n.robot.error;
    }
    if (!flag) {
        html += getLikeAndStepButtonHtml("", ROBOT_ID.KM);
    }
    sendFeedback(JSON.stringify(feedback));
    return html;
}

function handleEliteAIData(texts, flag) {
    var htmlArr = [];
    if (texts) {
        if (texts.code == 0)
            texts = texts.value;
        $.each(texts, function (i, text) {
            if (text.hasAnswer) {
                var html = '';
                if (text) {
                    var type = text.type;
                    switch (type) {
                        case 'text':
                            html = text.text;
                            html = html.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
                            html = wrapATagAddTarget(html);
                            html = '<div class="msg-text">' + html + '</div>';
                            break;
                        case 'choice':
                            var buttonType = text.buttonType;
                            html = '<div class="msg-text">' + text.text + '</div>';
                            if (text.choices) {
                                // html += "<br>";
                                $.each(text.choices, function (i, button) {
                                    if (buttonType == 1) {
                                        html += addclick((i + 1), button.title);
                                    } else {
                                        html += addclick(0, button.title);
                                    }

                                })
                            }
                            break;
                        case 'textImg':
                            html += domImageText.domImageTextHomeAppend();
                            $.each(text.textImg, function (i, item) {
                                var isFirst = false;
                                if (i == 0) isFirst = true;
                                html += domImageText.domImageText(item.menuTitleContent, item.menuHintContent, item.menuImgURL, item.menuContentURL, isFirst)
                            })
                            html += domImageText.domImageTextEndAppend();
                            break
                        case 'cmd':
                            if (!flag) {
                                var robotText = text.text;
                                if (robotText.indexOf("zrg") > -1) {
                                    if ($ROBOT.isPocVersion()) {
                                        $("#popDiv").show();
                                    } else {
                                        $ROBOT.transferChat($config.queueId, robotText);
                                    }
                                }
                            } else {
                                html = ORDER_MESSAGE;
                            }
                            break;
                        default:
                            html = text;
                            break;
                    }
                } else {
                    html = i18n.robot.error;
                }
                if (!flag && html) {
                    html += getLikeAndStepButtonHtml("", ROBOT_ID.ELIEAI);
                }
                // sendFeedback(JSON.stringify(feedback));
                htmlArr.push(html);
            }
        })
    } else {
        htmlArr.push(i18n.robot.error);
    }

    return htmlArr;
}

function handleZTEROBOTData(text, flag) {

    var account = UCSSSOAccount || ZTEDPGSSOUser;
    if (account == "") {
        var cookies = document.cookie;
        if (cookies.length > 0) {
            var cookieArr = cookies.split(";");
            $.each(cookieArr, function (i, cookie) {
                var param = cookie.trim().split('=');
                if (param[0] == 'UCSSSOAccount') {
                    UCSSSOAccount = param[1];
                } else if (param[0] == 'ZTEDPGSSOUser') {
                    ZTEDPGSSOUser = param[1];
                }
            });
        }
        account = UCSSSOAccount || ZTEDPGSSOUser;
    }

    var html = "";
    var htmlData = ' data-reason="" data-advice="" ';
    if (!text) {
        html = i18n.robot.error;
    }
    text = text.result;
    if (text.reply) {
        htmlData += ' data-answer="' + encodeURIComponent(text.reply) + '" ';
        html = text.reply;
    }
    if (text.rawQuery) {
        htmlData += ' data-query="' + encodeURIComponent(text.rawQuery) + '" ';
    }
    html = html.replaceAll("\\t", "").replaceAll("\n", "");
    if (html == '') {
        if (text.recommends) {
            var recommendResult = text.recommends;
            if (recommendResult.length > 0) {
                html += i18n.robot.relatedQuestions;
                $.each(recommendResult, function (i, recommend) {
                    html += addclick(i + 1, recommend.question);
                })
            }
        }
    }
    if (html == '') {
        if (robotEngineConfig.noAnswerMessage)
            html = robotEngineConfig.noAnswerMessage;
    }
    if (account) {
        htmlData += ' data-account="' + account + '" ';
        html += getLikeAndStepButtonHtml("", ROBOT_ID.ZTEROBOT, htmlData);
    }
    // sendFeedback(JSON.stringify(feedback));
    return html;
}

function handleSinoROBOTData(text, flag) {
    var html = "";
    if (!text) {
        html = i18n.robot.error;
    }
    if (text) {
        var result = text.result;
        if (result == 0) {
            var answerTypeId = text.answerTypeId;
            if (answerTypeId == 6) { //直接回答
                if (text.singleNode) {
                    var singleNode = text.singleNode;
                    var answerMsg = singleNode.answerMsg;
                    var isRichText = singleNode.isRichText;
                    if (isRichText == 1) {
                        var xmlDoc = $.parseXML(answerMsg), $xml = $(xmlDoc), $item = $xml.find("root");
                        html += domImageText.domImageTextHomeAppend();
                        $.each($item, function (i, item) {
                            var isFirst = false;
                            if (i == 0) isFirst = true;
                            html += domImageText.domImageText(wrapCDATA($(item).find('Title')[0].textContent),
                                wrapCDATA($(item).find('Description')[0].textContent),
                                wrapCDATA($(item).find('PicUrl')[0].textContent),
                                wrapCDATA($(item).find('Url')[0].textContent), isFirst)
                        })
                        html += domImageText.domImageTextEndAppend();
                    } else {
                        html = answerMsg;
                    }
                    if (singleNode.cmd) {
                        if (!flag) {
                            var cmd = singleNode.cmd;
                            if (cmd.toUpperCase().indexOf("ZRG") > -1) {
                                $ROBOT.transferChat($config.queueId, cmd);
                            }
                            if (cmd.toUpperCase().indexOf("IVR") > -1) {
                                $ROBOT.transferChat($config.queueId, cmd);
                            }
                        }
                    }
                }
                if (text.vagueNode) {
                    var vagueNode = text.vagueNode;
                    html += vagueNode.promptVagueMsg;
                    var listItems = vagueNode.itemList;
                    $.each(listItems, function (i, listItem) {
                        html += addclick(i + 1, listItem.question);
                    })
                    html += vagueNode.endVagueMsg;
                }
            } else { //1  系统错误 2  答案缺失 3  无法回答 4  有敏感词 5 推荐回答  7  模式匹配  8命中图谱 9  命中场景 10 聊天过频
                if (text.singleNode) {
                    var singleNode = text.singleNode;
                    html = singleNode.answerMsg;
                    if (singleNode.cmd) {
                        var cmd = singleNode.cmd;
                        if (cmd.toUpperCase().indexOf("ZRG") > -1) {
                            html = html + getNoticeForTransferMessageWhenRejectRecog();
                        }
                        if (cmd.toUpperCase().indexOf("IVR") > -1) {
                            html = html + getNoticeForTransferMessageWhenRejectRecog();
                        }
                    }
                }
                if (text.vagueNode) {
                    var vagueNode = text.vagueNode;
                    html += vagueNode.promptVagueMsg;
                    var listItems = vagueNode.itemList;
                    $.each(listItems, function (i, listItem) {
                        html += addclick(i + 1, listItem.question);
                    })
                    html += vagueNode.endVagueMsg;
                }
            }
            var serviceLogId = text.serviceLogId;
            if (serviceLogId) {
                htmlData = ' data-serviceLogId="' + serviceLogId + '" ';
                html += getLikeAndStepButtonHtml("", ROBOT_ID.SINOROBOT, htmlData);
            }

        } else {
            html = i18n.robot.error;
        }
    }
    if (html == '') {
        if (robotEngineConfig.noAnswerMessage)
            html = robotEngineConfig.noAnswerMessage;
    }

    // sendFeedback(JSON.stringify(feedback));
    return html;
}

function handleEemotiBOTData(text, flag) {
    var html = "";
    if (!text) {
        html = i18n.robot.error;
    }
    if (text) {
        var status = text.status;
        if (status == 200) {
            var datas = text.data;
            $.each(datas, function (i, data) {
                var type = data.type;
                var subType = data.subType;
                if (type == 'text') { //直接回答
                    if ('text' == subType) {
                        html += data.value;
                    } else if ('recommend' == subType) {
                        var dataRecommends = data.data;
                        $.each(dataRecommends, function (j, remmend) {
                            html += remmend.replyText;
                        })
                    }
                } else if (type == 'cmd') { //命令
                    if (subType == 'human') {
                        if (!flag && typeof _mid == 'undefined') {
                            $ROBOT.transferChat($config.queueId, data.answerType);
                            feedback = false;
                        }
                    }
                }
            })
        } else {
            html = i18n.robot.error;
        }
    }
    if (html == '') {
        if (robotEngineConfig.noAnswerMessage)
            html = robotEngineConfig.noAnswerMessage;
    }
    if (!flag && feedback) {
        var customInfo = text.customInfo;
        var dom = 'data-uuid= "' + (customInfo.uuid || '') + '"';
        html += getLikeAndStepButtonHtml("", ROBOT_ID.EMOTIBOT, dom);
    }
    // sendFeedback(JSON.stringify(feedback));
    return html;
}

function handleYunwBOTData(text, flag) {
    var property = robotEngineConfig.property;
    var original = false;
    if (property.original) {
        original = property.original;
    }
    var html = "";
    if (text.status == 0) {
        var data = text.data;
        var serviceType = data.serviceType;
        var robotReply = data.robotReply;
        robotReply = robotReply[0];
        var msgType = robotReply.msgtype;
        switch (msgType) {
            case 'text':
                var content = robotReply.text;
                html = content.content;
                break;
            case 'image':
                var image = robotReply.image;
                html = getImageHtml(image.url, image.name);
                html += image.content;
                break;
            case 'voice':
                var voice = robotReply.voice;
                html = '<div class="message-voice" data-url="' + voice.url + '" ></div>';
                html += voice.content;
                break;
            case 'video':
                var video = robotReply.video;
                html = '<div class="mobileVideo" data-url="' + video.url + '">' +
                    '<span>video.name</span>' +
                    '<i class="play far fa-play-circle"></i>' +
                    '</div>';
                html += video.content;
                break;
            case 'news':
                var news = robotReply.news;
                html += domImageText.domImageTextHomeAppend();
                $.each(news.articles, function (i, article) {
                    var isFirst = false;
                    if (i == 0) isFirst = true;
                    html += domImageText.domImageText(article.title, article.description, article.picurl, article.url, isFirst);
                })
                html += domImageText.domImageTextEndAppend();
                break;
            case 'guide':
                var guide = robotReply.guide;
                if (original) {
                    if (guide.beforeWord)
                        html += guide.beforeWord;
                    $.each(guide.list, function (i, listItem) {
                        html += addclick(listItem.seq, listItem.question);
                    })
                    if (guide.afterWord)
                        html += guide.afterWord;
                } else {
                    if (guide.content)
                        html += guide.content;
                }

                break;
            case 'richText':
                var richText = robotReply.richText;
                if (original) {
                    html += richText.original
                } else {
                    html += domImageText.domImageTextHomeAppend();
                    html += domImageText.domImageText(richText.title, richText.description, richText.picurl, richText.url, true);
                    html += domImageText.domImageTextEndAppend();
                }
                break;
            default:
                html = JSON.parse(robotReply);
                break;
        }
        if (robotReply.recommendQuestion) {
            var recommendQuestion = robotReply.recommendQuestion;
            if (recommendQuestion.beforeWord)
                html += recommendQuestion.beforeWord;
            $.each(recommendQuestion.list, function (i, listItem) {
                html += addclick(listItem.seq, listItem.question);
            })
            if (recommendQuestion.afterWord)
                html += recommendQuestion.afterWord;
        }
        if (robotReply.satisfaction) {
            html += robotReply.satisfaction;
        }
        if ('seat' == serviceType && !flag) {
            $ROBOT.transferChat($config.queueId, "");
        }
    } else {
        html = text.message
    }
    html = $EMOTION.parseToUnicode(html);
    return html;
}

function handleECHATBOTData(text, flag) {
    var html = JSON.stringify(text);
    if (text) {
        if (typeof text == "string") {
            text = JSON.parse(text);
        }
        if (text.plainContent)
            text = text.plainContent;
        var msgType = text.msgType;
        if (msgType) {
            switch (msgType) {
                case 'text':
                    var content = text.text;
                    html = content.content;
                    break;
                case 'image':
                    var image = text.image;
                    html = getImageHtml(image.picUrl, '');
                    break;
                case 'voice':
                    var voice = text.voice;
                    html = '<div class="message-voice" data-url="' + voice.fileUrl + '" data-length="' + voice.duration + '" ></div>';
                    break;
                case 'video':
                    var video = text.video;
                    html = '<div class="mobileVideo" data-url="' + video.fileUrl + '">' +
                        '<span>video.name</span>' +
                        '<i class="play far fa-play-circle"></i>' +
                        '</div>';
                    break;
                case 'file':
                    var file = text.file;
                    html = '<a href = "' + file.fileUrl + '" target = "_blank" class="attachment">' + file.fileName + '</a>';
                    break;
                case 'news':
                    var news = text.news;
                    html = domImageText.domImageTextHomeAppend();
                    html += domImageText.domImageText(news.title, news.content, news.imageUrl, news.url, true);
                    html += domImageText.domImageTextEndAppend();
                    break;
                case 'location':
                    var location = text.location;
                    html = '<div class="message-location" data-latitude="' + location.locationX + ' data-longitude="' + location.locationY + ' data-address="' + location.label + '"></div>';
                    break;
                case 'robotSimilarMatch':
                    if (text.hint)
                        html = text.hint;
                    if (text.suggestions) {
                        var suggestions = text.suggestions;
                        $.each(suggestions, function (i, suggestion) {
                            html += addclick(i + 1, suggestion.question);
                        })
                    }
                    break;
                case 'regChat':
                    html = '';
                    break;
                case 'endChat':
                    html = '';
                    break;
                case 'chatStarted':
                    html = '';
                    break;
                case 'chatEnded':
                    html = '';
                    break;
                case 'commitEvaluate':
                    html = '';
                    break;
                case 'transferCmd':
                    if (!flag && typeof _mid == 'undefined') {
                        var content = text.content;
                        $ROBOT.transferChat($config.queueId, content);
                        html = "";
                    } else {
                        html = text.content;
                    }
                    break;
                default:
                    var content = text.content;
                    if (content) {
                        html = content;
                    }
                    break;
            }
        }
    }
    return html;
}

function handleDKNTBOTData(text, flag) {
    var html = JSON.stringify(text);
    if (text) {
        if (typeof text == "string") {
            text = JSON.parse(text);
        }
        var msgType = text.msgType;
        if (msgType) {
            switch (msgType) {
                case 'text':
                    html = text.content;
                    break;
                case 'image':
                    var image = text.image;
                    html = getImageHtml(image.picUrl, '');
                    break;
                case 'voice':
                    var voice = text.voice;
                    html = '<div class="message-voice" data-url="' + voice.fileUrl + '" data-length="' + voice.duration + '" ></div>';
                    break;
                case 'video':
                    var video = text.video;
                    html = '<div class="mobileVideo" data-url="' + video.fileUrl + '">' +
                        '<span>video.name</span>' +
                        '<i class="play far fa-play-circle"></i>' +
                        '</div>';
                    break;
                case 'file':
                    var file = text.file;
                    html = '<a href = "' + file.fileUrl + '" target = "_blank" class="attachment">' + file.fileName + '</a>';
                    break;
                case 'news':
                    var news = text.news;
                    html = domImageText.domImageTextHomeAppend();
                    html += domImageText.domImageText(news.title, news.content, news.imageUrl, news.url, true);
                    html += domImageText.domImageTextEndAppend();
                    break;
                case 'location':
                    var location = text.location;
                    html = '<div class="message-location" data-latitude="' + location.locationX + ' data-longitude="' + location.locationY + ' data-address="' + location.label + '"></div>';
                    break;
                case 'cmd':
                    console.log("指令消息");
                    break;
                default:
                    var content = text.content;
                    if (content) {
                        html = content;
                    }
                    break;
            }
        }
    }
    return html;
}

/**
 * 1、富文本模版（TEXT：10000）
 2、折叠模版（FOLD：10001）
 3、图文模版（LINK: 10010）
 4、选择模版（SELECT：10018）
 5、流程表单模版（FLOWFORM：10019）
 6、快捷卡片（QUICKCARD：10016）
 7、猜你想问（GUESSCARD：10017）
 8、天气模版（sysWeather ：10005）
 * @param text
 * @param flag
 * @returns {string}
 */
function handleYANXIBOTData(text, flag) {
    var html = '', answerMessageId = '';
    var text = JSON.stringify(text);
    if (text) {
        if (typeof text == "string") {
            text = JSON.parse(text);
        }
        if (text.hasOwnProperty("robotAnswerLikeSwitch")) {
            likeButton = stepButton = text.robotAnswerLikeSwitch;
            return "";
        }

        var type = text.type;
        if ('chat_message' === type) {
            if (text.id)
                answerMessageId = text.id;
            var body = text.body;
            if (body && body.data) {
                var tplData = body.data.tplData;
                var nativeId = body.template.nativeId;
                switch (nativeId) {
                    case '10000': //富文本模版
                        html = tplData.html;
                        html = $EMOTION.filterEmojis(html);
                        break;
                    case '10001': //折叠模版
                        var options = tplData.options;
                        var classOrientation = tplData.orientation ? 'orientation' : '';
                        html = '<div class="relate_title ' + classOrientation + '">' + tplData.message + '</div>';
                        $.each(options, function (i, option) {
                            var answerType = option.answerType;
                            var optionValue = option.optionValue;
                            var optionName = option.optionName;
                            switch (answerType) {
                                case 1: //跳转链接
                                    html += domAnswerTitleAppend(optionName, optionValue, optionValue, i);
                                    break;
                                case 2: //模拟发送流程表单卡片
                                    html += domAnswerTitleAppend(optionName, optionValue, optionValue, i);
                                    break;
                                case 4: //关联图文链接卡片
                                    optionValue = optionValue.html;
                                    html += domAnswerTitleAppend(optionName, optionValue, optionValue, i);
                                    break;
                                default:
                                    break;

                            }
                            html += option.optionName;
                        })
                        break;
                    case '10010': //图文模版
                        html = domImageText.domImageTextHomeAppend();
                        html += domImageText.domImageText(tplData.title, tplData.description
                            , fileUrl + tplData.icon, tplData.link, true);
                        html += domImageText.domImageTextEndAppend();
                        break;
                    case '10018': //选择模版
                        var multiSelect = tplData.multiSelect;
                        if (multiSelect) {
                            html = '<div class="robot-card">';
                            html += '<div class="card-title">' +
                                '<span>' + tplData.message.html + '</span>' +
                                '</div>';
                            html += '<div class="card-content">';
                            $.each(tplData.items, function (i, item) {
                                html += '<div class="card-buttonItem" data-title="' + item.value + '">' +
                                    '<span>' + item.text + '</span>' +
                                    '</div>';
                            })
                            html += '</div>';
                            html += '<div class="card-button">' +
                                '<div class="card-flex1">' +
                                '<div class="card-btnSure card-sure" data-active="sure">确定</div>' +
                                '</div>' +
                                '<div class="card-flex1">' +
                                '<div class="card-btnSure card-unsure" data-active="no">不清楚</div>' +
                                '</div>' +
                                '</div>';
                            html += '</div>';

                        } else {
                            html = tplData.message.html;
                            $.each(tplData.items, function (i, item) {
                                html += '<div class="send-message" data-message="' + item.value + '">' + item.text + '</div>';
                            })
                        }
                        break;
                    case '10019': //流程表单模版
                        html = tplData.message;
                        var form = tplData.form;
                        html += "<br>" + form.title;
                        $.each(form.items, function (i, item) {
                            html += "<br>" + item.itemName;
                            html += item.itemValue.html;
                        })
                        var btns = tplData.btns;
                        $.each(btns, function (i, btn) {
                            if ('link' == btn.type) {
                                html += '<div class="robot-btn show-iframeUrl" data-url="' + btn.value + '">' + btn.text + '</div>';
                            } else if ('message' == btn.type) {
                                html += '<div class="robot-btn send-message" data-message="' + btn.value + '">' + btn.text + '</div>';
                            }
                        })
                        break;
                    case '10016': //快捷卡片
                        html = tplData.html;
                        break;
                    case '10017': //猜你想问
                        $.each(tplData.items, function (i, item) {
                            html += '<div class="send-message" data-message="' + item.value + '">' + item.text + '</div>';
                        })
                        break;
                    case '10005': //天气模版
                        html = tplData.message;
                        break;
                }
                if (body.transferIM) {  //需要转人工
                    var transferIMType = body.transferIMType;
                    if ('MANUAL' == transferIMType) {
                        html = html + getNoticeForTransferMessage();
                    } else if ('AUTO' == transferIMType) {
                        if (!flag && typeof _mid == 'undefined') {
                            var content = text.content;
                            $ROBOT.transferChat($config.queueId, code);
                        }
                    }

                } else {
                    if (!flag && html) {
                        var dom = 'data-evaluateType= "5" data-answerMessageId="' + answerMessageId + '"';
                        html += getLikeAndStepButtonHtml("", ROBOT_ID.YANXIBOT, dom);
                    }
                }
            }

        } else if ('event_message' == type) {
            var body = text.body;
            if (body.data) {
                var data = body.data;
                if (body.template) {
                    if (!flag && typeof _mid == 'undefined') {
                        var nativeId = body.template.nativeId;
                        switch (nativeId) {
                            case '10016':
                                var items = data.tplData.items;
                                if (items.length > 0) {
                                    var quickcardHtml = '<div class="quickcard"><div class="content">'
                                        + '<div class="ul">';
                                    $.each(items, function (i, item) {
                                        quickcardHtml += '<a class="li send-message"  data-message="' + item.text + '">'
                                            + '<div class="item">'
                                            + '<div class="topImg"><img class="avatar" src="' + fileUrl + item.params.icon + '"></div>'
                                            + '<div class="font">' + item.text + '</div>'
                                            + '</div>'
                                            + '</a>'
                                    })
                                    quickcardHtml += '</div></div"></div>';
                                    domImageText.appendDom(quickcardHtml);
                                }
                                break;
                            case '10017':
                                if (data.tplData) {
                                    var items = data.tplData.items;
                                    if (items.length > 0) {
                                        html += '<h4>' + i18n.page.guessYouWantAsk + '</h4>';
                                        $.each(items, function (i, item) {
                                            html += '<div class="send-message" data-message="' + item.value + '">' + item.text + '</div>';
                                        })
                                    }
                                }
                                break;
                        }
                    }
                } else {
                    var content = text.content;
                    var code = body.action.code;
                    if ("cfg.quickEntry" == code) { //快捷入口
                        var items = data.tplData.items;
                        if (items.length > 0) {
                            var keysHtml = '<ul>';
                            $.each(items, function (i, item) {
                                keysHtml += '<li data-type="' + (item.actionType || item.type) + '" data-value="' + item.text + '" class="key-text">' + item.text + '</li>';
                            })
                            keysHtml += '</ul>';
                            $(".keys-space").css("display", "flex");
                            $(".keys-space").html(keysHtml);
                        }
                    }
                }
            }
        }
    }
    return html;
}

function handleIFLYTEKBOTData(text, flag) {
    if (text) {
        if (typeof text == "string") {
            text = JSON.parse(text);
        }
        var ret = text.ret;
        if (ret == 0) {
            var outAction = text.outaction;
            if (outAction == 9) {
                var outParams = text.outparams;
                if (!flag) {
                    var toManual = outParams.toManual;
                    if (toManual == 1) {
                        $ROBOT.transferChat($config.queueId, '');
                        return;
                    }
                }
                var answer = outParams.answer;
                if (answer == 1) {
                    var answerType = outParams.answerType;
                    switch (answerType) {
                        case '0': // 纯文本
                            html = outParams.prompt_text;
                            break;
                        case '1': //富文本, GET请求下来, 做展示
                            html = outParams.resourceUrl.replaceAll("\\\\", "").replace("\"<p>", "").replace("</p>\"", "");
                            break;
                        case '2': // 单图片
                            html = outParams.prompt_text;
                            break;
                        case '3': // 图文页面
                            html = outParams.resourceUrl.replaceAll("\\\\", "").replace("\"<p>", "").replace("</p>\"", "");
                            break;
                        default:
                            html = i18n.robot.noAnswer;
                    }
                } else {
                    html = outParams.prompt_text || '';
                }
                if (outParams.prompt_guide)
                    html += '<br>' + (outParams.prompt_guide || '');
                var moreResult = outParams.more_result;
                if (moreResult && moreResult.length > 0) {

                    $.each(moreResult, function (i, result) {
                        html += '<span class="send-message" data-message="' + result.questionStd + '">' + result.questionStd + '</span>';
                    })
                } else {
                    var extendParams = outParams.extendParams;
                    if (extendParams) { //该属性是针对于扩展内容的需要讯飞提供固定格式来进行解析
                        var robotConfigProperty = robotEngineConfig.property,
                            language = robotConfigProperty.language ? robotConfigProperty.language : "zh_CN",
                            key = 'record_' + language;
                        var record = extendParams[key];
                        if (record) {
                            var records = record.split("#");
                            if (records.length > 0) {
                                if (outParams.prompt_guide) {
                                    html += '<br>' + outParams.prompt_guide;
                                }
                                $.each(records, function (i, result) {
                                    html += '<span class="send-message" data-message="' + result + '">' + result + '</span>';
                                })
                            }
                        }
                        if (!flag) {
                            var chatBot = extendParams.chatBot;
                            if (chatBot == 'Cso') {
                                $ROBOT.transferChat($config.queueId, '');
                            } else if (chatBot == 'Ending') {
                                if (!flag) {
                                    if ($config.mobile) {
                                        $('#backBtn').click();
                                    } else {
                                        $('#back_div').click();
                                    }
                                }
                            }
                        }
                    }
                }

            } else {
                html = i18n.robot.noAnswer;
            }
        } else if (ret == 5000 || ret == 5001 || ret == 5002 || ret == 5003 || ret == 5004) {
            if (!flag) {
                if (!errorFlag) {
                    errorFlag = true
                    sendMsgWithSearchKeyBase('faqvote:sys_err', 'sys_err');
                } else {
                    $ROBOT.transferChat($config.queueId, '');
                }

                return '';
            } else {
                html = i18n.robot.noAnswer;
            }

        }

    }
    return html;
}

var wrapURL = function (str) {
    if (!str) {
        return str;
    }
    var matchURLs = $('<div>').append(str).text().match(/(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g);
    if (matchURLs) {
        matchURLs = matchURLs.filter(function (item, index, self) {
            return self.indexOf(item) === index;
        });
        $.each(matchURLs, function (i, url) {
            try {
                //经过text()方法后，字符串中的&amp;会变成& 这里要判断一下，如果存在这种情况，就要再replace一次
                var parsedUrl = url.replace(/&/g, '&amp;').replace(/\?/g, '\\?');
                str = str.replace(new RegExp(parsedUrl, 'g'), function (matchStr) {
                    var url = matchStr;
                    if (!matchStr.startsWith('http://') && !matchStr.startsWith('https://')) {
                        url = 'http://' + matchStr;
                    }
                    return '<a target="_blank" href="' + url + '">' + matchStr + '</a>';
                });
            } catch (e) {
                console.log(e);
                return url;
            }

        });
    }
    return str;
};

function getData(postTime) {
    var now = new Date(postTime), seconds = now.getSeconds(), minutes = now.getMinutes();
    if (parseInt(seconds) < 10) seconds = '0' + now.getSeconds();
    if (parseInt(minutes) < 10) minutes = '0' + now.getMinutes();
    return now.getHours() + ":" + minutes + ":" + seconds;
};

var ROBOT_ID = {
    "KM": "BOT000",
    "YIBOT": "BOT001",
    "XIAOI": "BOT002",
    "XIAODUO": "BOT003",
    "SOBOT": "BOT004",
    "ELITEBOT": "BOT005",
    "EBOSSBOT": "BOT006",
    "ELIEAI": "BOT007",
    "ZTEROBOT": "BOT008",
    "SINOROBOT": "BOT009",
    "EMOTIBOT": "BOT010",
    "YUNWBOT": "BOT011",
    "ECHATBOT": "BOT012",
    "DKNTBOT": "BOT013",
    "YANXIBOT": "BOT014",
    "IFLYTEKBOT": "BOT015"
};

var ROBOT_FROM_TYPE = {
    "0": "BOT000",
    "1": "BOT001",
    "2": "BOT002",
    "3": "BOT003",
    "4": "BOT004",
    "5": "BOT005",
    "6": "BOT006",
    "7": "BOT007",
    "8": "BOT008",
    "9": "BOT009",
    "10": "BOT010",
    "11": "BOT011",
    "12": "BOT012",
    "13": "BOT013",
    "14": "BOT014",
    "15": "BOT015"
};

var domAnswerTitleAppend = function (title, question, answer, i) {
    return '<div class="each-message">' +
        '<div class="message-title" data-title = "' + title + '" data-question = \'' + (title || question) + '\' >' + (i + 1) + '. ' + (title || question) + '</div>' +
        '<div class="message-preview" style="display: none">' + answer + '</div>' +
        '</div>';
};

function wrapLink(answer, robotType, isHis, messageId, robotId, feedBackResult) {
    robotType = robotType || '', isHis = isHis || false, messageId = messageId || '', robotId = robotId || '', feedBackResult = feedBackResult || '';
    if (answer) {
        var extraDom = '';
        if (robotType) {
            extraDom = 'data-extra="' + robotType + '"';
        }
        var reg1 = new RegExp(/\[link(.*?)url="(.*?)"](.*?)\[\/link]/g);
        while (reg1.test(answer)) {
            answer = answer.replace(reg1, '<a ' + extraDom + ' href="$2" target="_blank">$3</a>');
        }
        var reg2 = new RegExp(/\[link(.*?)submit="(.*?)"](.*?)\[\/link]/g);
        while (reg2.test(answer)) {
            answer = answer.replace(reg2, '<a ' + extraDom + ' class="send-message" data-message="$3">$3</a>');
        }
        var reg3 = new RegExp(/\[link](.*?)\[\/link]/g);
        while (reg3.test(answer)) {
            answer = answer.replace(reg3, '<a ' + extraDom + ' class="send-message" data-message="$1">$1</a>');
        }
        var reg4 = new RegExp(/\[link(.*?)post="(.*?)"](.*?)\[\/link]/g);
        var rateFlag = false;
        if (reg4.test(answer)) {
            var revokeDom = '';
            if (!isHis) {
                revokeDom = ' data-revoke="' + messageId + '" ';
            }
            answer = answer.replace(reg4, function (a, k, v, b, c) {
                console.log('messageId is [%s], a ---  %s ,\nk ---  %s ,\nv ---  %s ,\nc ---  %s, \nb ---  %s', messageId, a, k, v, c, b);
                var active = '';
                if (v.indexOf(' 1 ') > 0) {
                    var feedback = true, likesStateClass = ''; //状态存在三种不可操作，已经操作， 可操作
                    if (!isHis) {
                        if (feedBackResult) {
                            feedback = false
                            likesStateClass = 'operabled'; //已经操作
                        } else {
                            likesStateClass = 'operable'; //可操作
                        }
                    } else {
                        feedback = false
                        likesStateClass = 'inoperable'; //不可操作
                    }
                    if (feedBackResult == 1) {
                        active = 'active';
                    }
                    return '<div class="rate-message likes ' + likesStateClass + '" data-feedback="' + feedback + '"><div>' +
                        '<div class="like" ' + extraDom + ' data-msg="' + b + '" data-search="' + v + '" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + ' data-post="1"' + revokeDom + '>' +
                        '<i class="' + active + '"></i>' + b
                        + '</div>';
                } else if (v.indexOf(' 2 ') > 0) {
                    var rateExtendFlag = _dissatisfactionReasons ? true : false;
                    rateFlag = true;
                    if (feedBackResult == 2) {
                        active = 'active';
                    }
                    var stepDom = '<div class="step" ' + extraDom + ' data-reason="' + rateExtendFlag + '" data-msg="' + b + '" data-search="' + v + '" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + ' data-post="2"' + revokeDom + '>' +
                        '<i class="' + active + '"></i>' + b
                        + '</div>' +
                        '</div>';

                    if (rateExtendFlag) {
                        stepDom += '<div class="step-extend hide">';
                        stepDom += '<div class="step-reason">';
                        stepDom += '<div class="reason-title">' + i18n.robot.stepReason + '</div>';
                        stepDom += '<div class="reason-main">';
                        $.each(JSON.parse(_dissatisfactionReasons), function (i, r) {
                            stepDom += '<div class="reason-li step-li" data-reason="false" ' + extraDom + ' data-msg="' + b + '" data-search="' + v.replace('{4}', r.REASON_DETAIL) + '" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + ' data-post="2"' + revokeDom + ' data-code="' + r.REASON_CODE + '" data-detail="' + r.REASON_DETAIL + '">' + r.REASON_DETAIL + '</div>';
                        })
                        stepDom += '</div>';
                        stepDom += '</div>';
                        stepDom += '</div>';
                    }
                    stepDom += '</div>';

                    return stepDom;
                } else {
                    if (isHis)
                        return '<a ' + extraDom + ' class="send-message">' + b + '</a>';
                    else
                        return '<a ' + extraDom + ' class="send-message" data-key="' + v + '" data-message="' + b + '">' + b + '</a>';
                }
            });
        }

        var reg5 = new RegExp(/\[link(.*?)submit="(.*?)"]/g);
        while (reg5.test(answer)) {
            answer = answer.replace(reg5, '<a ' + extraDom + ' class="send-message" data-message="$2">$2</a>');
        }
        var reg6 = new RegExp(/\[link(.*?)cmd="(.*?)"](.*?)\[\/link]/g);
        while (reg6.test(answer)) {
            answer = answer.replace(reg6, '<a ' + extraDom + ' class="send-message" data-cmd="$2">$3</a>');
        }
    }
    return answer
};

function wrapATag(str) {
    if (!$config.mobile) {
        var reg = new RegExp(/<a target="_blank" href="([^\]]*)\">([^\]]*)<\/a>/i);
        while (reg.test(str)) {
            str = str.replace(reg, '<a target=\\\"_blank\\\" href=\\\"$1\\\">$2</a>');
        }
    }
    return str;
};

function wrapATagAddTarget(str) {
    var reg = new RegExp(/<a href=([^\]]*)\>([^\]]*)<\/a>/i);
    while (reg.test(str)) {
        str = str.replace(reg, "<a target=\\\"_blank\\\" href=$1>$2</a>");
    }
    return str;
};

function wrapCDDATA(str) {
    var reg = new RegExp(/<\!\[CDATA\[([\S\s].*)\]\]>/i);
    while (reg.test(str)) {
        str = str.replace(reg, '$1').replace('<![CDATA[]]>', '');
    }
    return str;
};

function wrapClickMessage(str) {
    var reg = new RegExp(/^(?!.*<a)(.*?)【(.*?)】/g);
    while (reg.test(str)) {
        str = str.replace(reg, '$1<a class="send-message" data-message=\"$2\">$2</a>');
    }
    return str;
};

function delayNotice() {
    if (!$config.mobile) {
        $("#waitingForAcceptInChatView").show(10).delay(5500);
    }
};

var domImageText = {
    domImageTextHomeAppend: function () {
        return '<ul class="tb-view">';
    },

    domImageTextEndAppend: function () {
        return '</ul>';
    },

    domImageText: function (title, description, picUrl, url, isFirst) {
        var html = "";
        if (isFirst) {
            html += '<li class="tb-cell tb-cell_first"><a href="' + url + '" target="_blank">' +
                '<div class="first-img">' +
                '<img src="' + picUrl + '" alt="' + title + '" style="max-width: 300px; max-height: 300px;" class="tb-img fl" />' +
                '</div>';
        } else {
            html += '<li class="tb-cell"><a href="' + url + '" target="_blank">' +
                '<img src="' + picUrl + '" alt="' + title + '" style="max-width: 300px; max-height: 300px;" class="tb-img fl" />';
        }
        html += '<div class="tb-body">';
        html += '<p class="tb-title">' + title + '</p>';
        if (description) {
            html += '<p class="tb-content">' + description + '</p>';
        }
        html += '</div>';
        html += '</a></li>';
        return html;
    },
    setNotices: function (str) {
        if ($config.mobile) {
            $("#clientResponseDiv").append("<p class=\"messageTips\"><em>" + msg + "</em></p>");
        } else {
            $("#waitingForAcceptInChatView").html($F.formatTopNotice(str));
        }
    },
    appendDom: function (dom) {
        if ($config.mobile) {
            $("#clientResponseDiv").append(dom);
        } else {
            $F.appendTextToDiv("clientResponseDiv", dom);
        }
    }
};

var messageHtml = {
    "KM": function (text, flag) {
        return handleKMData(text, flag);
    },

    "YIOBT": function (text, flag) {
        return handleYibotData(text, flag);
    },

    "XIAOI": function (messageId, text, flag) {
        return handleXiaoIData(messageId, text, flag);
    },
    "XIAODUO": function (text, flag) {
        return handleXiaoDuoData(text, flag);
    },
    "SOBOT": function (text, flag) {
        return handleSobotData(text, flag);
    },
    "ELITEBOT": function (text, flag) {
        return handleElitebotData(text, flag);
    },
    "EBOSSKMBOT": function (text, flag) {
        return handleEbossKMbotData(text, flag);
    },
    "ELITEAI": function (text, flag) {
        return handleEliteAIData(text, flag);
    },
    "ZTEROBOT": function (text, flag) {
        return handleZTEROBOTData(text, flag);
    },
    "SINOROBOT": function (text, flag) {
        return handleSinoROBOTData(text, flag);
    },
    "EMOTIBOT": function (text, flag) {
        return handleEemotiBOTData(text, flag);
    },
    "YUNWBOT": function (text, flag) {
        return handleYunwBOTData(text, flag);
    },
    "ECHATBOT": function (text, flag) {
        return handleECHATBOTData(text, flag);
    },
    "DKNTBOT": function (text, flag) {
        return handleDKNTBOTData(text, flag);
    },
    "YANXIBOT": function (text, flag) {
        return handleYANXIBOTData(text, flag);
    },
    "IFLYTEK": function (text, flag) {
        return handleIFLYTEKBOTData(text, flag);
    }
}

window.$ROBOT = {
    init: function (robotEngine) {
        try {
            if (robotEngine) {
                if (typeof robotEngine == 'string') {
                    robotEngineConfig = JSON.parse(robotEngine);
                } else {
                    robotEngineConfig = robotEngine;
                }
                if (robotEngineConfig.property) {
                    var robotConfigProperty = robotEngineConfig.property;
                    if (robotConfigProperty.feedbackTips) {
                        feedbackTips = robotConfigProperty.feedbackTips;
                    }
                    if (robotConfigProperty.transferName) {
                        transferName = robotConfigProperty.transferName;
                    }
                    if (robotConfigProperty.transferTips) {
                        transferTips = robotConfigProperty.transferTips;
                    }
                    if (robotConfigProperty.hasOwnProperty('allowRate')) {
                        allowRateForClientCloseSession = robotConfigProperty.allowRate;
                    }
                    var clickHtml = getTransferClickHtml();
                    if (transferTips.indexOf('{0}')) {
                        transferTips = transferTips.replace('{0}', clickHtml);
                    }
                    if (robotConfigProperty.sessionRound) {
                        sessionRound = robotConfigProperty.sessionRound;
                    }
                    if (robotConfigProperty.sessionRoundTips) {
                        sessionRoundTips = robotConfigProperty.sessionRoundTips;
                    }
                    if (robotConfigProperty.isHiddenTransferHtml) {
                        isHiddenTransferHtml = robotConfigProperty.isHiddenTransferHtml;
                    }
                    if (robotConfigProperty.version) {
                        robotVersion = robotConfigProperty.version
                    }
                    if (robotConfigProperty.wework) {
                        isWework = robotConfigProperty.wework
                    }
                    if (robotConfigProperty.likeButton) {
                        likeButton = robotConfigProperty.likeButton;
                        if (likeButton) {
                            if (robotConfigProperty.likeButtonName) {
                                likeButtonName = robotConfigProperty.likeButtonName;
                            }
                        }
                    }
                    if (robotConfigProperty.stepButton) {
                        stepButton = robotConfigProperty.stepButton;
                        if (stepButton) {
                            if (robotConfigProperty.stepButtonName) {
                                stepButtonName = robotConfigProperty.stepButtonName;
                            }
                        }
                        if (robotConfigProperty.afterStepToShowTransferButton) {
                            afterStepToShowTransferButton = robotConfigProperty.afterStepToShowTransferButton;
                        }
                    }
                    if (robotConfigProperty.transeferButton) {
                        transferButton = robotConfigProperty.transeferButton;
                    }
                    if (robotConfigProperty.ordersPageSize) {
                        ordersPageSize = robotConfigProperty.ordersPageSize;
                    }
                    if (robotConfigProperty.orderHrefType) {
                        orderHrefType = robotConfigProperty.orderHrefType;
                    }
                    if (robotConfigProperty.fileUrl) {
                        fileUrl = robotConfigProperty.fileUrl;
                    }

                }
            }
        } catch (e) {
            robotLog(e.message, 'on robot init');
        }
    },
    getRobotVersion: function () {
        return robotVersion;
    },

    isPocVersion: function () {
        return robotVersion === 'poc';
    },

    transferingChange: function (flag) {
        $(".timeWait").hide();
        _transfering = flag;
        if ($config.queue.transferingNotInput && flag) {
            if ($config.mobile) {
                $("#clientResponseDiv").append("<p class=\"messageTips\" id=\"timer\"><span>" + i18n.common.minutes + "/" + i18n.common.seconds + "</span></p>")
                this.timeWait(function (numberMText, numberTimeText) {
                    $("#timer").html('<span>' + i18n.common.waitingTime + +numberMText + '：' + numberTimeText + i18n.common.minutes + '/' + i18n.common.seconds + '</span>');
                });
                $('#clientMessageBox').attr('contenteditable', !flag)
            } else {
                chatEditor.readonly(flag)
                $("#talkBox").append("<div class=\"no-bg no-yel\" id=\"timer\"><div class=\"notice\"><span>" + i18n.common.minutes + "/" + i18n.common.seconds + "</span></div></div>")
                this.timeWait(function (numberMText, numberTimeText) {
                    $("#timer .notice").html('<span>' + i18n.common.waitingTime + numberMText + '：' + numberTimeText + i18n.common.minutes + '/' + i18n.common.seconds + '</span>');
                });
                $('#clientMessageBox').attr('contenteditable', !flag)
            }
        } else {
            if (!flag) {
                $("#timer").remove();
                clearInterval(timerNum)
            }
        }
    },

    // 等待时长问题
    timeWait: function (callback) {
        var tips = ''
        var numberTime = 0;
        var numberM = 0;
        var numberMText = '';
        var numberTimeText = '';

        function PrefixInteger(num, m) {
            return (Array(m).join(0) + num).slice(-m);
        }

        if ($config.mobile) {
            timerNum = setInterval(function () {
                numberTime++;
                if (numberTime >= 60) {
                    numberM++
                    numberTime = 0
                }
                numberMText = PrefixInteger(numberM, 2);
                numberTimeText = PrefixInteger(numberTime, 2);
                if (numberTime >= 2 || numberM > 0) {
                    $('#orderInQueue span').remove()
                }
                callback(numberMText, numberTimeText)
            }, 1000);

        } else {
            timerNum = setInterval(function () {
                numberTime++;
                if (numberTime >= 60) {
                    numberM++
                    numberTime = 0
                }
                numberMText = PrefixInteger(numberM, 2);
                numberTimeText = PrefixInteger(numberTime, 2)
                callback(numberMText, numberTimeText);
            }, 1000);
        }

    },

    isuniqloVersion: function () {
        return 'uniqlo' == robotVersion;
    },

    dealData: function (content, userId, flag, messageId, feedBackResult) {
        messageId = messageId || '', feedBackResult = feedBackResult || '';
        var msgText = '';
        if (!content) return '';
        try {
            if (typeof content != 'object') {
                content = content.replaceAll('\r\n', '<br>').replaceAll('\n\r', '<br>').replaceAll('\r', '<br>').replaceAll('\n', '<br>').replaceAll('\b', ' ');
                content = wrapATag(content);
                try {
                    var isJson = JSON.parse(content);
                    if (typeof isJson == 'object' && isJson) {
                        content = isJson;
                    }
                } catch (e) {

                }
            }
            if (userId == ROBOT_ID.KM) {
                msgText = messageHtml.KM(content, flag);
            } else if (userId == ROBOT_ID.YIBOT) {
                msgText = messageHtml.YIOBT(content, flag);
            } else if (userId == ROBOT_ID.XIAOI) {
                if ('uniqlo' == robotVersion) {
                    msgText = messageHtml.XIAOI(messageId, content, flag);
                    msgText = wrapLink(msgText, content.robotType, flag, messageId, ROBOT_ID.XIAOI, feedBackResult);
                } else {
                    msgText = messageHtml.XIAOI(messageId, content, flag);
                    msgText = wrapLink(msgText);
                }
                if (msgText) {
                    msgText = msgText.replaceAll('\\[link]', '').replaceAll('\\[\/link]', '');
                }

            } else if (userId == ROBOT_ID.XIAODUO) {
                msgText = messageHtml.XIAODUO(content, flag);
            } else if (userId == ROBOT_ID.SOBOT) {
                msgText = messageHtml.SOBOT(content, flag);
            } else if (userId == ROBOT_ID.ELITEBOT) {
                msgText = messageHtml.ELITEBOT(content, flag);
            } else if (userId == ROBOT_ID.EBOSSBOT) {
                msgText = messageHtml.EBOSSKMBOT(content, flag);
            } else if (userId == ROBOT_ID.ELIEAI) {
                msgText = messageHtml.ELITEAI(content, flag);
            } else if (userId == ROBOT_ID.ZTEROBOT) {
                msgText = messageHtml.ZTEROBOT(content, flag);
            } else if (userId == ROBOT_ID.SINOROBOT) {
                msgText = messageHtml.SINOROBOT(content, flag);
            } else if (userId == ROBOT_ID.EMOTIBOT) {
                msgText = messageHtml.EMOTIBOT(content, flag);
            } else if (userId == ROBOT_ID.YUNWBOT) {
                msgText = messageHtml.YUNWBOT(content, flag);
            } else if (userId == ROBOT_ID.ECHATBOT) {
                msgText = messageHtml.ECHATBOT(content, flag);
            } else if (userId == ROBOT_ID.DKNTBOT) {
                msgText = messageHtml.DKNTBOT(content, flag);
            } else if (userId == ROBOT_ID.YANXIBOT) {
                msgText = messageHtml.YANXIBOT(content, flag);
            } else if (userId == ROBOT_ID.IFLYTEKBOT) {
                msgText = messageHtml.IFLYTEK(content, flag);
                msgText = wrapLink(msgText);
            } else {
                msgText = content;
            }
            if (userId != ROBOT_ID.XIAOI && userId != ROBOT_ID.ECHATBOT && userId != ROBOT_ID.IFLYTEKBOT && userId != ROBOT_ID.YANXIBOT) {
                msgText = wrapURL(msgText);
            }
        } catch (e) {
            msgText = content;
            robotLog(e, 'on error ->' + content);
        }
        if ('uniqlo' != robotVersion) {
            if (typeof msgText == 'string')
                msgText = wrapClickMessage(msgText);
        }

        hiddenTransferHtml();
        return msgText;
    },

    isRobot: function (userId) {
        return userId == ROBOT_ID.KM ||
            userId == ROBOT_ID.YIBOT ||
            userId == ROBOT_ID.XIAOI ||
            userId == ROBOT_ID.XIAODUO ||
            userId == ROBOT_ID.SOBOT ||
            userId == ROBOT_ID.ELITEBOT ||
            userId == ROBOT_ID.EBOSSBOT ||
            userId == ROBOT_ID.ELIEAI ||
            userId == ROBOT_ID.SINOROBOT ||
            userId == ROBOT_ID.ZTEROBOT ||
            userId == ROBOT_ID.YUNWBOT ||
            userId == ROBOT_ID.ECHATBOT ||
            userId == ROBOT_ID.DKNTBOT ||
            userId == ROBOT_ID.IFLYTEKBOT ||
            userId == ROBOT_ID.YANXIBOT ||
            userId == ROBOT_ID.EMOTIBOT;
    },

    notAllowShowRate: function (userId) {
        if (!userId) {
            return !allowRateForClientCloseSession;
        } else {
            if (this.isRobot(userId)) {
                return !allowRateForClientCloseSession;
            }
        }

        return false;
    },

    setMaxHisMessageId: function (messageId) {
        maxHisMessageId = messageId;
    },

    getRobotText: function (text, userId, flag, messageId, feedBackResult) {
        feedBackResult = feedBackResult || '';
        if (userId) {
            if ($ROBOT.isRobot(userId)) {
                var isNews = false;
                // var text = {
                //     "robotType": "hr",
                //     "similarity": 1,
                //     "buttonList": [],
                //     "moduleId": "core",
                //     "type": 1,
                //     "nodeId": "001611110779233019900017fa0316bb",
                //     "commands": [{
                //         "args": ["HR:213"],
                //         "name": "route",
                //         "state": 0
                //     }, {"args": ["见习", "期间", "什么时候", "开始"], "argNames": [], "name": "ai_segments", "state": 0}],
                //     "content": "当月25日前通过审核，则下月开始进入实习补助期。比如12月25日前申请通过，则1月1日起进入实习补助期间。\r\n\r\n<b>以上答案是否解决了您的问题？<\/b>[link post=\"faqvote:001611110779233019900017fa0316bb 1 vPvPsMbavOTKssO0yrG68r+qyryjvw== vPvPsMbavOTKssO0yrG68r+qyryjvw== tbHUwjI1yNXHsM2ouf3J87rLo6zU8s/C1MK/qsq8vfjI68q1z7Cyudb6xtqho7HIyOcxMtTCMjXI1cewyerH682ouf2jrNTyMdTCMcjVxvC9+MjryrXPsLK51vrG2rzkoaM= {4}\"]解决[/link] [link post=\"faqvote:001611110779233019900017fa0316bb 2 vPvPsMbavOTKssO0yrG68r+qyryjvw== vPvPsMbavOTKssO0yrG68r+qyryjvw== tbHUwjI1yNXHsM2ouf3J87rLo6zU8s/C1MK/qsq8vfjI68q1z7Cyudb6xtqho7HIyOcxMtTCMjXI1cewyerH682ouf2jrNTyMdTCMcjVxvC9+MjryrXPsLK51vrG2rzkoaM= {4}\"]未解决[/link]",
                //     "callbackParamType": 0,
                //     "props": {
                //         "sentiment": "0.00",
                //         "sessionId": "3a5f1940b8a54c3bb2c8d85b03a746f4",
                //         "categoryId": "c54907f9cd4f4b82959e9ac8dfd3f3e4",
                //         "objectId": "001611110779230019890017fa0316bb"
                //     },
                //     "relatedQuestions": []
                // };
                // var text = {"robotName":"hr","similarity":1,"buttonList":[{
                //         "question": "重复付款怎么办",
                //         "name": "人事部门",
                //         "type": "hr",
                //         "userId": "hexin1"
                //     }],"moduleId":"core","type":101,"nodeId":"001607334319699013260050569b69ba","commands":[{"args":["重复","付款","怎么办"],"argNames":[],"name":"ai_segments","state":0}],"content":{"acs":"ZGD","etype":"总部or门店","path":"分类"},"callbackParamType":0,"props":{"sentiment":"0.00","sessionId":"42c9bb360777423b92aadfe7be1f6505","categoryId":"27c4737a73fa4b7095c6b50107acdb5f","objectId":"001607334319697013230050569b69ba"},"relatedQuestions":["重复付款怎么办"]};

                // var text = {
                //     "content": "宝宝，我来了！请详细描述你要求助的问题，让我更好的帮助你哦！\n您是否遇到以下问题：\n[1] 配送时间\n[2] 怎么还没送到\n[3] 没收到货就显示签收了",
                //     "hint": "宝宝，我来了！请详细描述你要求助的问题，让我更好的帮助你哦！\n您是否遇到以下问题：",
                //     "mediaId": "SgmrqLefbIR8vLnS6CL",
                //     "msgType": "robotSimilarMatch",
                //     "suggestions": [{
                //         "knowledgeType": 1,
                //         "question": "配送时间"
                //     }, {
                //         "knowledgeType": 1,
                //         "question": "怎么还没送到"
                //     }, {
                //         "knowledgeType": 1,
                //         "question": "没收到货就显示签收了"
                //     }],
                //     "userId": "13666150888",
                //     "userType": 1,
                //     "visitorId": "webvip13666150888"
                // }
                var text = $ROBOT.dealData(text, userId, flag, messageId, feedBackResult);
                if (typeof text == "object") {
                    if (!$.isArray(text)) {
                        text = text.html;
                    }
                }
            } else {
                if (typeof text == 'string') {
                    if (text.startWith('faqvote:')) {
                        text = i18n.robot.faqvote;
                    }
                }
                text = $ROBOT.parseFormattedMsg(text);
            }
        }

        return text;
    },

    wanUrl: function () {
        if (robotEngineConfig) {
            return robotEngineConfig.wanUrl || '';
        } else {
            return '';
        }
    },

    robotOrderObj: {},  //序列号和关键字对应的key value 值

    orderNumToKey: function (num) {
        if ('uniqlo' == robotVersion && isWework) return num;
        var rs = num;
        $.each($ROBOT.robotOrderObj, function (key, value) {
            if (num == key) {
                rs = value;
            }
        });
        return rs;
    },
    /**
     * 解析格式化的消息
     *
     * [MessageFormat data-type="robot" data-key="BOT002"]{"commands":[{"argNames":[],"args":["胃炎","胃炎","https://uat.aia.com.cn/robot/attachments/20180807114344698"],"name":"imgmsg","state":1}],"content":"","relatedQuestions":["胃炎","核保各类疾病问卷"],"similarity":1,"type":1}[/MessageFormat]
     * [MessageFormat data-type="robot" data-key="BOT002"]{"commands":[{"argNames":[],"args":["https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/articles.xml","1","UTF-8","&lt;![CDATA[&lt;Articles&gt;&lt;item&gt;&lt;Title&gt;&lt;![CDATA[龙腾出行介绍]]&gt;&lt;/Title&gt;&lt;Description&gt;&lt;![CDATA[]]&gt;&lt;/Description&gt;&lt;PicUrl&gt;&lt;![CDATA[https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/imgmsgItem1.png?t=1525418670697]]&gt;&lt;/PicUrl&gt;&lt;Url&gt;&lt;![CDATA[https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/index_1.html?t=1525418676026]]&gt;&lt;/Url&gt;&lt;/item&gt;&lt;/Articles&gt;]]&gt;"],"name":"imgtxtmsg","state":1}],"content":"","relatedQuestions":["VIP机场贵宾室","龙腾出行如何使用"],"similarity":1,"type":1}[/MessageFormat]
     */
    parseFormattedMsg: function (formattedMsg, mesageStyleClass) {
        var resultMsg = formattedMsg;
        try {
            var regexp = /^\[MessageFormat([^\]]*)\]([\s\S]*)\[\/MessageFormat\]$/;
            var ret = regexp.exec(formattedMsg);
            if (ret && ret.length === 3) {
                var props = ret[1], msgContent = ret[2], pos, propsMap = {};
                props = props.trim().replace(/\s+/g, ' ').split(' ');

                props.forEach(function (p) {
                    if ((pos = p.indexOf('=')) > 0) {
                        var key = p.substring(0, pos);
                        var value = p.substring(pos + 1).trim();
                        value = value.replace(/"/g, '');
                        propsMap[key] = value;
                    } else {
                        propsMap[p] = true;
                    }
                });

                var dataType = propsMap['data-type'];
                if (dataType === 'robot') {
                    var robotId = propsMap['data-key'];
                    msgContent = $ROBOT.parseHtmlEntity(msgContent);
                    resultMsg = $ROBOT.dealData(msgContent, robotId, true);
                }
                //[MessageFormat data-type="imgText" data-key="1919"]{"content": "一行描述", "title": "我是图文消息", "imageUri": "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png", "url": "http://www.baidu.com"}[/MessageFormat]
                else if ('imgText' == dataType) {
                    var msgContentJSON = JSON.parse(msgContent);
                    var content = msgContentJSON.content; //需要显示的来源
                    var title = msgContentJSON.title; //需要显示的来源
                    var imageUri = msgContentJSON.imageUri; //需要显示的来源
                    var url = msgContentJSON.url; //需要显示的来源
                    resultMsg = domImageText.domImageTextHomeAppend();
                    resultMsg += domImageText.domImageText(title, content, imageUri, url, true);
                    resultMsg += domImageText.domImageTextEndAppend();
                    resultMsg = '<div class="message-imgtext" data-url="' + url + '">' +
                        '<div class="title">' + title + '</div>' +
                        '<div class="content">' +
                        '<div class="desc">' +
                        '<div class="wrapper">' + content + '</div>' +
                        '</div>' +
                        '<img class="thumb" src="' + imageUri + '">' +
                        '</div>' +
                        '</div>';
                }
                //[MessageFormat data-type="card" data-key="1919"]{"from": "来源天猫", "title": "我是卡片消息", "imageUri": "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png", "url": "http://www.baidu.com", "price": "12.00"}[/MessageFormat]
                else if ('card' == dataType) {
                    var msgContentJSON = JSON.parse(msgContent);
                    var from = msgContentJSON.from; //需要显示的来源
                    var title = msgContentJSON.title; //需要显示的标题
                    var imageUri = msgContentJSON.imageUri; //显示的图片地址
                    var url = msgContentJSON.url; //点击之后跳转的地址
                    var price = msgContentJSON.price; //需要显示的价格
                    resultMsg = '<div class="message-card" data-url="' + url + '">' +
                        '<div class="card-image"><img class="thumb" src="' + imageUri + '"></div>' +
                        '<div class="card-content">' +
                        '<p class="card-price">' + price + '</p>' +
                        '<p class="card-title">' + title + '</p>' +
                        '<p class="card-from">' + from + '</p>' +
                        '</div>' +
                        '</div>'
                }

                //[MessageFormat data-type="orders" data-key="1919"][{"content":"一行描述","title":"我是图文消息","imageUri":"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png","orderId": "订单号123456","orderStatus": "订单状态","size": "XXXXL", "color": "太空灰", "price": "￥2000", "url":"http://www.baidu.com"},{"content":"一行描述","title":"我是图文消息","imageUri":"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png","orderId": "订单号123456","orderStatus": "订单状态","size": "XXXXL", "color": "太空灰", "price": "￥2000", "url":"http://www.baidu.com"}, {"content":"一行描述","title":"我是图文消息","imageUri":"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png","orderId": "订单号123456","orderStatus": "订单状态","size": "XXXXL", "color": "太空灰", "price": "￥2000", "url":"http://www.baidu.com"}][/MessageFormat]
                else if ('orders' == dataType) {
                    var msgContentArr = JSON.parse(msgContent);
                    var from = propsMap['data-from'] || '';
                    var keyFrom = propsMap['data-key'] || '';
                    var title = propsMap['data-title'] || '';
                    if (msgContentArr.length > 0) {
                        var pageCount = msgContentArr.length, pageSize = Math.ceil(pageCount / ordersPageSize);
                        resultMsg = "", orderIdPrev = "";
                        if (title)
                            resultMsg += '<div class="orders-title"><div>' + title + '</div></div>';
                        $.each(msgContentArr, function (i, msgContentJSON) {
                            var content = msgContentJSON.content ? msgContentJSON.content : ""; //需要显示的来源
                            var orderId = msgContentJSON.orderId ? msgContentJSON.orderId : ""; //需要显示的来源
                            var key = msgContentJSON.key ? msgContentJSON.key : ""; //需要显示的来源
                            var orderStatus = msgContentJSON.orderStatus ? msgContentJSON.orderStatus : ""; //需要显示的来源
                            var size = msgContentJSON.size ? msgContentJSON.size : ""; //尺寸
                            var quantity = msgContentJSON.quantity ? msgContentJSON.quantity : ""; //件数
                            var color = msgContentJSON.color ? msgContentJSON.color : ""; //尺寸
                            var price = msgContentJSON.price ? msgContentJSON.price : ""; //尺寸
                            var title = msgContentJSON.title ? msgContentJSON.title : ""; //需要显示的来源
                            var imageUri = msgContentJSON.imageUri ? msgContentJSON.imageUri : ""; //需要显示的来源
                            var url = msgContentJSON.url ? msgContentJSON.url : ""; //需要显示的来源
                            var funca = msgContentJSON.funca ? msgContentJSON.funca : ""; //需要显示的来源
                            var funci = msgContentJSON.funci ? msgContentJSON.funci : ""; //需要显示的来源
                            var send = msgContentJSON.send ? msgContentJSON.send : ""; //需要显示的来源
                            var noReasonFlag = msgContentJSON.noReasonFlag ? msgContentJSON.noReasonFlag : ""; //需要显示的来源
                            var hideClass = ordersPageSize > i ? '' : 'hidden';
                            resultMsg += '<div class="message-orders ' + hideClass + '" data-index="' + parseInt(i / ordersPageSize) + '" data-url="' + url + '" data-funca="' + funca + '" data-funci="' + funci + '" data-send="' + send + '" data-keyfrom="' + keyFrom + '" data-from="' + from + '" data-key="' + key + '">';
                            if (i % ordersPageSize) {
                                orderIdPrev = '';
                            }
                            if (orderId && orderId != orderIdPrev) {
                                resultMsg += '<div class="order-head">' +
                                    '<div class="order-id">' + orderId + '</div>' +
                                    '<div class="order-status">' + orderStatus + '</div>' +
                                    '</div>';
                            }
                            orderIdPrev = orderId;

                            resultMsg += '<div class="order-container">' +
                                '<div class="orders-left">' +
                                '<img class="thumb" src="' + imageUri + '">' +
                                '</div>' +
                                '<div class="orders-right">' +
                                '<div class="order-title">' + title + '</div>' +
                                '<div class="order-content">';
                            if (size)
                                resultMsg += '<div class="order-size">尺寸：' + size + '</div>';
                            if (color)
                                resultMsg += '<div class="order-color">颜色：' + color + '</div>';
                            // if (content)
                            //     resultMsg += '<div class="order-wrapper">' + content + '</div>';
                            if (noReasonFlag) {
                                noReasonFlag = (noReasonFlag == 'Y') ? i18n.robot.orders.noReasonFlagY : i18n.robot.orders.noReasonFlagN;
                                resultMsg += '<div class="order-wrapper">' + noReasonFlag + '</div>';
                            }
                            if (price)
                                resultMsg += '<div class="order-price">￥ ' + price + '</div>';
                            if (quantity)
                                resultMsg += '<div class="order-color">x' + quantity + '</div>';
                            resultMsg += '</div>' +
                                '</div>' +
                                '</div>' +
                                '</div>';
                        });

                        if (pageCount > ordersPageSize) {
                            resultMsg += '<div class="order-footer" data-page="0" data-size="' + pageSize + '">' +
                                ' <span class="next orders-button" data-type="next">' + i18n.robot.orders.buttonNext + '</span>' +
                                ' <span class="prev orders-button" data-type="prev">' + i18n.robot.orders.buttonPrev + '</span>' +
                                '</div>';
                        }
                    }

                }
            } else {
                resultMsg = wrapURL(formattedMsg);
            }
        } catch (e) {
            robotLog(e.message, 'on parseFormattedMsg');
        }
        return resultMsg;
    },

    parseHtmlEntity: function (msg) {
        if (msg) {
            msg = msg.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
        }
        return msg;
    },

    transferChat: function (queue, transferInfo) {
        $ROBOT.transferingChange(true)
        robotLog(_transfering, '_transfering');
        Constants.robot.isRobot = false;
        if ($config.queue.permFlag == '1') {
            createPrivateChat(queue);
        } else {
            var robotId = ROBOT_FROM_TYPE[robotEngineConfig.type];
            transferInfo = transferInfo ? encodeURIComponent(transferInfo) : '';
            if ($config.mobile) {
                robotTransferToQueue(robotId, queue, transferInfo)
            } else {
                $F.robotTransferToQueue(robotId, queue, transferInfo);
            }
        }
    },
    transferDialog: function (message, confirmFunc, cancelFunc) {
        if ($config.mobile) {
            setTimeout(function () {
                layer.open({
                    content: i18n.page.transferTip
                    , className: 'confirm-mobile'
                    , btn: [i18n.page.dialog.yes, i18n.page.dialog.cancel]
                    , yes: function (index) {
                        if ($.isFunction(confirmFunc)) {
                            confirmFunc();
                        }
                        layer.close(index)
                    }
                    , no: function (index) {
                        if ($.isFunction(cancelFunc)) {
                            cancelFunc();
                        }
                        layer.close(index)
                    }
                });
            }, 1000)
        } else {
            var confirmContainer = $('.confirm-container');
            var bg_cover = $('.bg_cover');
            if (confirmContainer.length > 0) {
                if (message) {
                    $('.confirm-container .msg').html(message);
                } else {
                    $('.confirm-container .msg').html(i18n.page.transferTip);
                }

                confirmContainer.show();
                $('.bg_cover').show();
            } else {
                var hei = $("html").height();
                var wid = $("html").width();
                var mheight = (hei - 150) / 2;
                var mwidth = (wid - 300) / 2;

                confirmContainer = $('<div class="confirm-container" style="height: 150px"><div class="msg">' + i18n.page.transferTip +
                    '</div><div class="btn-container"><a class="confirm-btn zrg-button">' + i18n.page.dialog.yes + '</a><a class="cancel-btn">' + i18n.page.dialog.cancel + '</a></div></div>').css({
                    "left": mwidth,
                    "top": mheight
                });
                $("body").append(confirmContainer);

                $('.confirm-container .zrg-button').off('click').on('click', function () {
                    event.stopPropagation();
                    UI.hideChangeModule();
                    confirmContainer.hide();
                    bg_cover.hide();
                    if ($.isFunction(confirmFunc)) {
                        confirmFunc();
                    }
                    UI.cuestomerService();
                    $(confirmContainer).remove();
                });

                $('.confirm-container .cancel-btn').off('click').on('click', function () {
                    event.stopPropagation();
                    confirmContainer.hide();
                    bg_cover.hide();
                    $('.bg_cover').hide();
                    if ($.isFunction(cancelFunc)) {
                        cancelFunc();
                    }
                    $(confirmContainer).remove();
                });
                bg_cover.show();
            }
        }
    }
}
})
(jQuery);
